These is a cheatsheet of the memory layout of some common pattens in virtual inheritance.
For each case there is first the code.
Then there is a diagram.
On the left there is a representation of the inheritance relationships.
Gold color means virtual.
On the right there is the memory layout.
The dashed arrows represent where a pointer of that type would point if a casting was performed.
At the bottom of this page there is a collection of links. Some of them are good for a first contact, and other go very in depth.
1
struct Widget
{
int widget;
};
struct Button
: public Widget
{
int button;
}
2
struct Widget
{
int widget;
virtual void f(){}
};
struct Button
: public Widget
{
int button;
}
3
struct Widget
{
int widget;
};
struct Button
: public virtual Widget
{
int button;
}
4
struct Widget
{
int widget;
virtual void f(){}
};
struct Button
: public virtual Widget
{
int button;
}
5
struct Widget
{
int widget;
};
struct Prop1 { int prop1; };
struct Prop2 { int prop2; };
struct Prop3 { int prop3; };
struct Button
: public Widget
, public Prop1
, public Prop2
, public Prop3
{
int button;
};
6
struct Widget
{
int widget;
};
struct Prop1
: public virtual Widget
{
int prop1;
};
struct Prop2
: public virtual Widget
{
int prop2;
};
struct Prop3
: public virtual Widget
{
int prop3;
};
struct Button
: public Prop1
, public Prop2
, public Prop3
{
int button;
};
7
struct Widget
{
int widget;
};
struct Prop1
: public virtual Widget
{
int prop1;
};
struct Prop2
: public virtual Widget
{
int prop2;
};
struct Prop3
: public virtual Widget
{
int prop3;
};
struct Button
: public virtual Widget
, public Prop1
, public Prop2
, public Prop3
{
int button;
};
Same memory layout.
8
struct Widget
{
int widget;
virtual void f(){}
};
struct Prop1
: public virtual Widget
{
int prop1;
};
struct Prop2
: public virtual Widget
{
int prop2;
};
struct Prop3
: public virtual Widget
{
int prop3;
};
struct Button
: public virtual Widget
: public Prop1
, public Prop2
, public Prop3
{
int button;
};
Links
Good as introduction:
This series explores virtual inheritance at the low level. Goes really in depth: memory layout and assemble code. This is the best resource I found. It also teaches you how to use GDB to get the answers yourself.
Other useful resources:
-
https://cs.nyu.edu/courses/fall16/CSCI-UA.0470-001/slides/MemoryLayoutMultipleInheritance.pdf
-
http://www.drdobbs.com/cpp/multiple-inheritance-considered-useful/184402074?pgno=1
-
https://hownot2code.com/2016/08/12/good-and-bad-sides-of-virtual-inheritance-in-c/
Some interesting stackoverflow questions:
- https://stackoverflow.com/questions/11603198/virtual-tables-and-memory-layout-in-multiple-virtual-inheritance
- https://stackoverflow.com/questions/28521242/memory-layout-of-a-class-under-multiple-or-virtual-inheritance-and-the-vtables