q0987
q0987

Reputation: 35982

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

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

Upvotes: 6

Views: 4325

Answers (2)

Alok Save
Alok Save

Reputation: 206566

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

Upvotes: 10

Xeo
Xeo

Reputation: 131829

The virtual table pointer is just a pointer inside every object of your class, pointing to the correct virtual table. Inside the virtual table are the addresses for the virtual functions of your class. The compiler traverses the virtual table to get the correct function when invoking a function through a base class pointer.

Upvotes: 4

Related Questions