#Previous question #Index of C++ Questions #Next question

vfptr, vftable, virtual functions

C++ compiler creates a hidden class member called virtual-pointer or in short vfptr when there are one or more virtual functions. This vfptr is a pointer that points to a table of function pointers. This table is also created by compiler and called virtual function table or vftable. Each row of the vftable is a function pointer pointing to a corresponding virtual function.

VFPTRVFTABLEFUNCTION
b.vfptr ->Vftable[0] ->base::funct1()
Vftable[1] ->base::funct2()

To accomplish late binding, the compiler creates this vftable table for each class that contains virtual functions and for the class derived from it. The compiler places the addresses of the virtual functions for that particular class in "vftable".

When virtual function call is made through a base-class pointer, the compiler quietly inserts code to fetch the VFPTR and look up the function address in the VFTABLE, thus calling the right function and causing late/dynamic binding to take place.

Compiler assigns at construction

class base 
{
  virtual void funct1(void);
  virtual void funct2(void);
};
/* Object */
base b;
/* C++ Compiler internally Does this*/
b.vptr = address of b.vtable;
b.vtable[0]= &base::funct1;
b.vtable[1]= &base::funct2;

Pictorial View

vptr, vtable, virtual functions

Printing vfptr, vtables source code

#include <iostream>
using namespace std;
class base
{
  public:
  virtual void funct1(void) = 0;
  virtual void funct2(void) = 0;
};
class derived : public base
{
  public:
  derived()
  { 
    cout << "Object constructed" <<endl;
    cout << "Object address is "<< this <<endl;
    cout << "vfptr address is "<< *(void**)this <<endl;
    cout << "funct1 address is "<< *(void**)(*(void**)this) <<endl;
    cout << "funct2 address is "<< *((void**)(*(void**)this)+1) <<endl;
  }
  void funct1(void);
  void funct2(void);
};
void derived::funct1(void)
{
}
void derived::funct2(void)
{
}
int main (int argh, char *argv[])
{
  
  derived d;
  void *** vfptr = (void ***) &d;
  void ** vtable = (void **)*vfptr;
  cout << "From main" <<endl;
  cout << "Address of d is " << &d << endl;
  cout << "vfptr is " << vtable << endl;
  cout << "Address of funct1 is " << vtable[0] << endl;
  cout << "Address of funct2 is " << vtable[1] << endl; 
  return 0; 
}

Output

Object constructed
Object address is 0x7ffeec14cb28
vfptr address is 0x103ab5110
funct1 address is 0x103ab3cb0
funct2 address is 0x103ab3cc0
From main
Address of d is 0x7ffeec14cb28
vfptr is 0x103ab5110
Address of funct1 is 0x103ab3cb0
Address of funct2 is 0x103ab3cc0

You have viewed 1 page out of 62. Your C++ learning is 0.00% complete. Login to check your learning progress.

Most popular topics (must visit)

Useful links for students