Virtual table/Virtual function in C++

  • Note that those functions not carrying the keyword virtual in their declaration do not generally appear in the virtual method table.
  • Whenever a class itself contains virtual functions or overrides virtual functions from a parent class the compiler builds a vtable for that class.
  • The Virtual table contains the array of function pointers (address of function) that point to the virtual functions in that class.
  • There can be only be one vtable per class, and all objects of the same class will share the same vtable.
  • For any class that contain a vtable, the compiler will also add virtual pointer which point to that virtual table of that class. It is maintained per object.
  • The linking of Non virtual functions are processed during compilation i.e. static binding/early binding.
  • 2 virtual table will be created that is 1 for base class and another for derived class. But, compiler set only one public VPTR in base class internally. If 2nd Vtable is required to be initialized then the same VPTR is inherited and used at run time. Note that Constructors initializes the VPTR.
    So, only 1 public VPTR in base class.

class Animal

{

public:

       virtual void getWeight() { cout << “Animal Weight”; }

       void getHeight() { cout << “Animla Height”; }

       virtual ~Animal(){}

};

class Tiger : public Animal

{

       int *p;

public:

       Tiger() {p = new int();}

       void getWeight() { cout << “Tiger Weight”; }

       virtual ~Tiger( delete p;){}

};

void virtualTest()

{

       Animal *a = new Tiger();

       a->getWeight();

       /*     The call above gets translated to this, assuming the pointer to the

              vtable for the Tiger class is called vptr1

              :

              *(a->vptr1->getWeight())

       */

}

Why virtual constructor not created in C++

The virtual mechanism works only when we have a base class pointer to a derived class object.

In C++, the constructor cannot be virtual, because when a constructor of a class is executed there is no virtual table in the memory, means no virtual pointer defined yet. So, the constructor should always be non-virtual.

But virtual destructor is possible. As virtual destructor maintains the hierarchy of calling destructors from derived class to base class.

For Example:

Animal *a = new Tiger();

delete a;

if we don’t make base class destructor virtual, it will not call derived class destructor i.e. ~Tiger() and memory of Tiger.p will not be deleted on above mentioned criteria.

  • 23
    Shares