Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory layout of a class under multiple or virtual inheritance and the vtable(s)?

I am reading "Inside the C++ Object Model", trying to understand how multiple and virtual inheritance is achieved via the vtables.(I understand single polymorphism perfectly-well).

I am having difficulties understand what exactly is done when a method needs to be located during virtual inheritance, or during casting, because there is a lot of offset calculation to be performed.

Would somebody be able to help with understanding how the multiple vtables are used in a multiple or virtual inheritance example? If I could understand the layout and the problem, I could probably understand this issue better.

like image 654
mezamorphic Avatar asked Feb 14 '15 22:02

mezamorphic


People also ask

Where is vtable memory stored?

Vtables themselves are generally stored in the static data segment, as they are class-specific (vs. object-specific).

What are multiple inheritances virtual inheritance )?

Virtual inheritance is used when we are dealing with multiple inheritance but want to prevent multiple instances of same class appearing in inheritance hierarchy. From above example we can see that “A” is inherited two times in D means an object of class “D” will contain two attributes of “a” (D::C::a and D::B::a).

What is stored in vtable?

For every class that contains virtual functions, the compiler constructs a virtual table, a.k.a vtable. The vtable contains an entry for each virtual function accessible by the class and stores a pointer to its definition. Only the most specific function definition callable by the class is stored in the vtable.

What is the size of vtable?

The size of an object is determined by its member variables and the padding and the presence of virtual functions or bases. @In silico: right, For class C, does it insert f3 in the both vtables inherited from A, B? If not, C should have one more vtable making its size 12 bytes.


1 Answers

C++ implementations generally use vtables to implement virtual functions. A vtable is a table of pointers to functions. Each object of a class with virtual functions has a hidden pointer to the vtable containing the addresses of all the virtual functions of the class.

When invoking a virtual function, the code calculates the offset of the function pointer in the vtable, and calls the function which address is stored there.

enter image description here

When a derived class of the base class overides a virtuall function, the virtual table of that class just points to the overidden function instead of the original one.

This excellent article explains in details how it work, both for single and multiple inheritance.

like image 129
Christophe Avatar answered Oct 26 '22 18:10

Christophe