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
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?
YESvptr
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?
YESVtbl
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With