What is vTable?

The vTable, or Virtual Table, is a table of function pointers that is created by the compiler to support dynamic polymorphism. Whenever a class contains a virtual function, the compiler creates a Vtable for that class. Each object of the class is then provided with a hidden pointer to this table, known as Vptr.

The Vtable has one entry for each virtual function accessible by the class. These entries are pointers to the most derived function that the current object should call.

vTable And vPtr in C++

In C++, runtime polymorphism is realized using virtual functions. But have you ever wondered how virtual functions work behind the scenes? The C++ language uses Vtable and Vptr to manage virtual functions. In this article, we will understand the concepts of Vtable and Vptr in C++.

What is Polymorphism?

In OOPs, polymorphism refers to the ability of objects to have names but different functionality. The most common use is with base class pointers or references calling derived class functions. This is called runtime polymorphism and is implemented in C++ using virtual functions.

Virtual Functions in C++

A virtual function is a member function that is declared within a base class with the virtual keyword and is re-defined (Overridden) by a derived class. When a class contains a virtual function, it can be overridden in its derived class and tells the compiler to perform dynamic linkage (or late binding) on the function. Now, the virtual functions are implemented in C++ by using vTable and vPtr.

Similar Reads

What is vTable?

The vTable, or Virtual Table, is a table of function pointers that is created by the compiler to support dynamic polymorphism. Whenever a class contains a virtual function, the compiler creates a Vtable for that class. Each object of the class is then provided with a hidden pointer to this table, known as Vptr....

What is vPtr (Virtual Pointer)?

The virtual pointer or _vptr is a hidden pointer that is added by the compiler as a member of the class to point to the VTable of that class. For every object of a class containing virtual functions, a vptr is added to point to the vTable of that class. It’s important to note that vptr is created only if a class has or inherits a virtual function....

Understanding vTable and vPtr Using an Example

Here is a simple example with a base class Base and classes Derived1 derived from Base and Derived2 from class Derived1....