Search code examples
c++multiple-inheritancevtable

How does vtable handle multiple inheritance?


I understand that for single inheritance a pointer to a virtual function table is added to determine what parent class functions to call at runtime.

class Genius {
    int IQ;
public:
    virtual void brag();
};

class Me : public Genius {
    int age;
};

When instantiated, the memory layout of Me should look something like

  pointer to Genius vtable
  int iq
  int age

But what happens in the case of multiple inheritance?

// Assume CoolDude has virtual functions as well
class Me : public Genius, public CoolDude {
    int age;
};

What does the memory layout of the Me class look like now? How is multiple inheritance handled?


Solution

  • The class will have 2 pointers to vtables, one to its implementation of Genius and one to its implementation of CoolDude. When casting to a base class, the the returned pointer will differ from the original by the offset of the vtable(and other members) or the base class.