Vptr and vtbl related to object or class?

vptr - virtual table pointer

vtbl - virtual table

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

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

Question 3> How do they really work together?

thanks

+4
source share
2 answers

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).

+6
source

A virtual table pointer is just a pointer inside each object of your class that points to the correct virtual table. Inside the virtual table are the addresses of the virtual functions of your class. The compiler bypasses the virtual table to get the correct function when calling the function using the base class pointer.

+2
source

Source: https://habr.com/ru/post/1345657/


All Articles