18

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.

intrigued_66
  • 16,082
  • 51
  • 118
  • 189
  • when you say multiple inheritance, do you mean having successive dervivations (c inherits from b which inherits from a) or do you mean real multiple inheritance (c inherits simultaneously from a an b) ? – Christophe Feb 14 '15 at 23:22
  • 1
    Maybe this question helps http://stackoverflow.com/q/11603198/1741542 – Olaf Dietsche Feb 14 '15 at 23:24

1 Answers1

17

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.

Christophe
  • 68,716
  • 7
  • 72
  • 138
  • 2
    This answers only for singly inheritance. What if we have `class B: virtual public A{` ? – Bogdan Mart Jan 24 '19 at 20:08
  • 1
    @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. – Christophe Jan 24 '19 at 21:01
  • I came here looking for multiple inheritance with virtual class inheritance. Am I missing something or are you explaining plain virtual functions? – NirIzr Nov 20 '19 at 12:12
  • @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. – Christophe Nov 20 '19 at 12:46