Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ -- vptr & vtbl associated with object or class?

Tags:

c++

vptr -- virtual table pointer

vtbl -- virtual table

Question 1> Is it correct that vptr is associated with the object of a class?

Question 2> Is it correct that vtbl is associated with the class?

Question 3> How do they really work together?

Thank you

like image 483
q0987 Avatar asked Mar 29 '11 04:03

q0987


1 Answers

Note that vptr and vtbl are Implementation defined the C++ standard does not even talk about them. However, most known compilers implement dynamic dispatch through vptr and vtbl.

Question 1: Is it correct that vptr is associated with the object of a class?

YES
vptr is associated with the object of a Class which contains Atleast one virtual member function. The compiler adds Vptr to every object of the Class which is Polymorphic(contains atleast one virtual member function)The first 4 bytes of the this pointer then point to the vptr

Question 2: Is it correct that vtbl is associated with the class?

YES
Vtbl is associated with a Class. A vtbl gets created for each Polymorphic class.

Question 3: How do they really work together?

The compiler adds a vptr to every object of a Polymorphic class and also creates a vtbl for each of that class. The vptr points to the vtbl. The vtbl contains a list of addresses of all the virtual functions in that class. In case if a derived class overrides a virtual function of the Base Class then the address entry for that particular function in the vtbl is replaced by the address of the overridden function. At runtime the compiler traverses the vtbl of the particular class(Base or Derived) based on the address inside the pointer rather than the type of pointer and calls the function address in the vtbl. Thus Dynamic Polymorphism is achieved.
The cost of this dynamic polymorphism is:
fetch(fetch the vptr inside this) fetch(fetch the function address from list of functions in vtbl) Call(Call the function)

as against call(direct call to function since static binding).

like image 65
Alok Save Avatar answered Sep 30 '22 02:09

Alok Save