Cpp Tutorial: Working of Vtable and _vptr in C++

In this chapter we shall learn about vtable and _vptr in C++.

vtable and _vptr is used to support runtime polymorphism or dynamic binding.

Few Points about Vtable:

vtable is also called as virtual table.
vtable is used as lookup table during runtime.
vtable gives the information about the function binding.
All the class that has a virtual function or derived class using virtual function will have it’s own vtable.
vtable is created at compile time and is used at run time.
vtable will be having function pointer entry to all the virtual functions present and derived in the class.
vtable will store NULL value for pure virtual function.

Few Points about _vptr:

vptr is also known as vtable pointer. This pointer will point to vtable.
vptr will be declared in base class and will be inherited in all the derived class.
A call to virtual function during runtime will be made using vptr to call the correct function.

In the below example, we shall see how vtable and vptr are created.

In below example, we have 1 base class “Base” and 2 derived classes “Derived_1” and “Derived_2”.

#include <iostream>
// for more tutorials visit www.ProDeveloperTutorial.com

using namespace std;

class Base  
 {  
 public:  
    virtual void function1() {cout<<"Base :: function1()\n";};  
    virtual void function2() {cout<<"Base :: function2()\n";};  
    virtual ~Base(){};
};  
   
class Derived_1: public Base  
{  
public:  
   ~Derived_1(){};
   virtual void function1() { cout<<"Derived_1 :: function1()\n";};
};  
  
class Derived_2: public Base  
{  
public:  
   ~Derived_2(){};
   virtual void function2() { cout<< "Derived_2 :: function2\n";};  
};  

int main()
{
    //creating an object of Derived_1 class
  Derived_1 *dObj = new Derived_1;;
  
  // assigning the object to base class pointer
  Base *b = dObj; 

  b->function1();
  b->function2();

  delete (b);
  
  return (0);
}

Output:

Derived_1 :: function1()
Base :: function2()

The vtable and vptr relationship can be visualized as below:

Vtable and _vptr in C++

Here the Base class virtual table will be having the address of base class functions.

As in Derived_1 class, it has only overridden function1(), in Derived_1 class vtable, function1() will be having the address of Derived_1 class, and function2() will be having Base classs function2() address.

Similarly in Derived_2 class, it has only overridden function2(), in Derived_2 class vtable, function2() will be having the address of Derived_2 class, and function1() will be having Base classs function1() address.

_vptr will be created in base class and then it will be derived in Derived_1 and Derived_2 classes.

Note:

Whenever there are virtual functions, make sure to make destructor of base class as virtual. Else the sequence of destructor call will be undefined.

 

 

 

 

 

 

 

 

 

 

 

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *