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

mezamorphic picture mezamorphic · Feb 14, 2015 · Viewed 10.5k times · Source

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.

Answer

Christophe picture Christophe · Feb 15, 2015

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.