Search code examples
c++multiple-inheritancevtablememory-layoutvptr

where is the overridden virtual method saved in the vtable c++ in multiple inheritance


In C++, there is no class representation at run-time but I can always call an overridden virtual method in the derived class. where is that overridden method saved in the vtable? here's a piece of code to demonstrate:

struct B1 {
 virtual void f() { ... }
};
struct B2 {
 virtual void f() { ... }
 virtual void g() { ... }
};
struct D : B1, B2 {
 void f() { ... }
 virtual void h() { ... }
};

What's the memory layout for an object of class D ? Where are B1::f and B2::f saved in that memory layout (if they're saved at all) ?


Solution

  • An object d of Class D will have only a pointer to the VMT of class D, which will contain a pointer to D::f. Since B1:f and B2::f can be called only statically from the scope of D class, there is no need for object d to keep a dynamic pointer to those overridden methods.

    This of cause is not defined in the standard, this is just the usual/logical implementation of the compiler.

    In fact the picture is more complicated, since the VMT of class D incorporates the VMTs of classes B1 and B2. But anyway, there is no need to dynamically call B1::f until an object of class B1 is created.