C++ virtual inheritance diagrams and links

2019/05/12

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;
}
1.svg

2

struct Widget
{
    int widget;
    virtual void f(){}
};

struct Button
    : public Widget
{
    int button;
}
2.svg

3

struct Widget
{
    int widget;
};

struct Button
    : public virtual Widget
{
    int button;
}
3.svg

4

struct Widget
{
    int widget;
    virtual void f(){}
};

struct Button
    : public virtual Widget
{
    int button;
}
4.svg

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;
};
5.svg

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;
};
6.svg

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.

7.svg

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;
};
8.svg

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:

Some interesting stackoverflow questions:

>> Home