Virtual Inheritance Memory Layouts
I am trying to fully understand what is happening under the hood in the memory with virtual inheritance and vTables/vPtrs and what not.
I have two examples of code I have written and I understand exactly why they work however I just want to make sure I have the right idea in my mind, of the object memory layouts.
Here are the two examples in a picture, and I just wish to know if my idea of the memory layouts involved are correct.
Example 1:
class Top { public: int a; };
class Left : public virtual Top { public: int b; };
class Right : public virtual Top { public: int c; };
class Bottom : public Left, public Right { public: int d; };
Example 2:
Same as above, but with:
class Right : public virtual Top {
public:
int c;
int a; // <======= added this
};
The C++ standard doesn't say much about the object layout. Virtual function tables (vtables) and virtual base pointers are not even part of the standard. So the question and the asnwers can only illustrate possible implementations.
A quick look on your drawing seems to show a correct layout.
You could be interested in these further references:
Multiple Inheritance Considered Useful a ddj article about layout in the case of multile inheritance and virtual inheritance.
Microsoft patent describing the use of vfptr (virtual function tables, aka vtables) and vbptr (virtual base poitners).
Edit: Does Bottom inherit
Right::a
orLeft::a
?In your test 2,
Right
andLeft
share the same common parentTop
. So there is only one subobjectTop
withinBottom
, and consequently, there is only one and the sameTop::a
.Interestingly, you've introduced in your test 2 a member
a
inRight
. This is ana
which is different from thea
inherited fromTop
. It's a distinct member, and just has the same name as another membemr "by coincidence". So if you accessa
via theRight
,Right::a
hides theTop::a
(which is by the way also theBottom::Top::a
, theRight::Top::a
, theLeft::Top::a
). In this case, bottom.a means the Right::a, not because of the object layout, but because of the name loockup (and hiding) rules. And this is not implementation dependent: it's standard and portable.Here a variant for your test 2 to demonstrate the situation: