Virtual function and vtable in C++

If a class declares a function as virtual then compiler constructs the vtable or Virtual Table for that class which stores addresses if virtual funcrions.
If any other classes derives from that class then they creates their own vtable.
The compiler also adds a hidden vptr variable in all such classes.
If a virtual function is not overridden in derived class then vtable stores address of its parent class function.

  • vtable stores static array of virtual functions, so that different instances of the same class can share that vtable. 
  • Since, static members are stored in the data section (.data), the vtable is also stored in the data section of the executable.
  • vtable is used to resolve the address of the function when virtual function is called at run-time.
  • Dynamic binding in C++ is achieved through vtable.

If derived class object is assigned to base object pointer, the vptr variable is points to vtable of the derived class. This ensures that derived virtual functions get called.

Example:

class Base
{
    public:
     virtual void display()
     {
         std::cout << "Base:: display()";
     }
};


class Derived : publid Base
{
   public:
   void display()
   {
       std::cout << "Derived::display()";
   }
};


void main()
{
   Base *b = new Base;
   b->display();

  Derived *d = new Derived();
  d->display();

  Base  *b1 = new Derived();
   b1->display();
}


Output:

Base::display()
Derived::display()
Derived::display()