Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mechanism of Vptr and Vtable in C++

In C++, during dynamic binding, consider the following example...

class Base
{
  virtual void fun()
  {
     cout<<"Base";
  }      
};

class Derived : public Base
{
   void fun()
   {
     cout<<"Derived";
   }
};

int main()
{
  Base *bptr;
  Derived d;
  bptr=&d;
  bptr->fun();
}

The output of the above function is "Derived" due to the declaration of virtual keyword/dynamic binding.

As per my understanding, a virtual table (Vtable) would be created which contains the address of the virtual functions. In this case the virtual table created for the derived class points to the inherited virtual fun(). And bptr->fun() will be getting resolved to bptr->vptr->fun();. This points to the inherited base class function itself. I am not completely clear on how the derived class function is called?

like image 719
Blue Diamond Avatar asked Oct 07 '13 11:10

Blue Diamond


People also ask

How does vtable and VPTR work?

# Vtable is created by compiler at compile time. # VPTR is a hidden pointer created by compiler implicitly. # If base class pointer pointing to a function which is not available in base class then it will generate error over there. # Memory of Vtable and VPTR gets allocated inside the process address space.

What is VPTR and vtable where it stored?

Vtable and Vptr is creating at compile time which will get memory in run time and vtable entries are virtual function addresses . Every object of a class containing a virtual function will have an extra pointer which is pointing to Virtual Table is known as virtual pointer.

What is a vtable in C?

A virtual method table (VMT), virtual function table, virtual call table, dispatch table, vtable, or vftable is a mechanism used in a programming language to support dynamic dispatch (or run-time method binding).


Video Answer


2 Answers

Just went through this link virtual table and _vptr

It says that the workflow will be like ..

  1. base_ptr->base_vptr----> to check the access of virtual function in base class.

  2. base_ptr->derived_vptr->virtual_function()---> to call/invoke the virtual function.

Hence the derived class virtual function is called.. Hope you find it helpful.

like image 61
Santosh Sahu Avatar answered Oct 12 '22 23:10

Santosh Sahu


And bptr->fun() will be getting resolved to bptr->vptr->fun();. This points to the base class function itself.

Wrong. The Derived instance's vptr (a hidden field in each instance) points to the Derived vtable.

like image 44
Kos Avatar answered Oct 12 '22 22:10

Kos