What is Vtable & Vptr in C++

Vtable contains the addresses of virtual functions.The compiler creates a Vtable for each class that contains virtual functions and for classes that are derived from it.The Vtable contains the addresses in the order in which virtual functions are defined with in the class.

Let us understand the Vtable with the help of the following example:

class shape
{
   public:
          virtual void draw1()
          {
          }
          virtual void draw2()
          {
          }
};
class circle:public shape
{
   public:
          void draw1()
          {
          }
          void draw2()
          {
          }
};
void main()
{
   shape *p,q;
   circle c;
   p=&q;
   p->draw2();
   p=&c;
   p->draw2();
}

whenever we create an object of the class,the class gets loaded into the memory and the Vtable gets created.In this program we have created an object of shape as well as of circle.Hence there will be two Vtables in memory.

The address of the Vtable stored in the object Vptr.

No comments:

Post a Comment