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

10,929

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.

Share:
10,929
mezamorphic
Author by

mezamorphic

Updated on June 05, 2022

Comments

  • mezamorphic
    mezamorphic almost 2 years

    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.

  • Bogdan Mart
    Bogdan Mart over 5 years
    This answers only for singly inheritance. What if we have class B: virtual public A{ ?
  • Christophe
    Christophe over 5 years
    @BogdanMart I tried to answer the main question of the OP. For the advanced case of MI, including virtual inheritance, I kindly invite you to read the article to which I linked. It provides all the needed details.
  • NirIzr
    NirIzr over 4 years
    I came here looking for multiple inheritance with virtual class inheritance. Am I missing something or are you explaining plain virtual functions?
  • Christophe
    Christophe over 4 years
    @NirIzr Since the question is quite broad, I asked in comment a refining question and had another question ready, to see how specific my answer had to be. OP didn’t answer my first question, so I I explained how the vtable and offsets are calculated (second part of the question) and referred to an article which explains how the right vtable is found in the case of MI and VI. Both together cover all the question. If you are interested specifically in VI, the article linked in the answer may help.