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.
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
/* Object */
/* C++ Compiler internally Does this*/
b.vptr = address of b.vtable;
Printing vfptr, vtables source code
virtualvoid funct1(void)= 0;
virtualvoid funct2(void)= 0;
class derived : public base
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;
int main (int argh,char*argv)
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<< endl;
cout <<"Address of funct2 is "<< vtable<< endl;
Object address is 0x7ffeec14cb28
vfptr address is 0x103ab5110
funct1 address is 0x103ab3cb0
funct2 address is 0x103ab3cc0
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.