Lets consider the following example
#include <iostream>
class Base {
public:
virtual void foo() {
std::cout << "Base::foo()" << std::endl;
}
};
class Derived : public Base {
public:
void foo() override {
std::cout << "Derived::foo()" << std::endl;
}
};
int main() {
Base* basePtr = new Derived();
basePtr->foo();
delete basePtr;
return 0;
}
So when Derived class was allocated memory, a vptr
was created inside Derived class that is pointing to the vtable
inside the derived class. Now vtable
contained the address of virtual function in the Derived class.
My question is basePtr
itself is of type Base
. How is it able to access the vptr
which is present inside the Derived class. Because if basePtr
tries accessing non virtual member function of derived class, we would have gotten compiler error. Then why not while accessing member variable vptr
of Derived
class?
After researching on this topic a bit, here is the general overview that I understood. Please feel free to edit answer if you find any mistake.
vptr
is typically stored as a hidden variable within each object of a class that has virtual functions. It is not stored directly within either the base or derived class itself, but within each object that is instantiated from the class.During runtime, when virtual functions are called through a base class pointer or reference, the vptr is used to access the correct vtable and resolve the appropriate virtual function based on the
actual object's type.
i.e the type of object stored in pointer.