Note that vptr and vtbl are the implementations described in the C ++ standard, not even talking about them. However, most well-known compilers implement dynamic dispatch via vptr and vtbl .
Question 1: Is it correct that vptr is associated with a class object?
Yes
vptr is associated with an object of the class that contains Atleast one virtual member function. The compiler adds Vptr to each object of the class that is Polymorphic (contains at least one virtual member function). The first 4 bytes of this then point to vptr
Question 2: Is it right that vtbl is associated with the class?
Yes
vtbl is associated with the class. A vtbl is created for each Polymorphic class.
Question 3: How do they work together?
The compiler adds vptr to each object of the Polymorphic class, and also creates vtbl for each of this class. vptr points to vtbl . vtbl contains the address list of all virtual functions of this class. In case the derived class redefines the virtual function of the base class, the address entry for this particular function in vtbl is replaced by the address of the redefined function. At run time, the compiler traverses the vtbl particular class (Base or Derived) based on the address inside the pointer, not the type of the pointer, and calls the address of the function in vtbl . Thus, Dynamic polymorphism is achieved.
The cost of this dynamic polymorphism:
fetch (vptr fetch inside this) fetch (select function address from function list in vtbl) Call (function call)
against Call (direct function call from the moment of static binding).
source share