Before learning vtable and vptr let us refresh the basic concept of virtual function. virtual function is a member function of a class declare with virtual keyword.

  • The ISO C++ Standard specifies that all virtual functions or methods of a class that are not pure-virtual must be defined. for example below code would not compile

vtable and vptr

vtable and vptr in c++ virtual function

So we are getting an error “undefined reference to vtable”. what does this error means? The base class Base requires an vtable. who will make this vtable object? The error will go out when we will provide the implementation of virtual function in Base class. C++ compiler creates a hidden class member called virtual-pointer or in  short vptr when there are one or more virtual functions. This vptr is a  pointer that points to a table of function pointers known as VTABLE.

  • vtable stores the address of virtual functions.
  • The address of the vtable stored in the object and this object is known as vptr.
  • The compiler creates a vtable for each class that contains virtual functions and for the classes that are derived from it.

Let us see another example for more discussion

Q. How many vtables should be created for the above sample code?

Ans: Two, as The compiler creates a vtable for each class that contains virtual functions and for the classes that are derived from it.

vtable-and-vptr-in-c

  •  The above figure shows that there are two vtables one for Base class and another for derived class.
  • when object (bobj) of class Base is created , its vtable gets created and vtable’s address gets stored in the first two bytes of the object (bobj).