Kam
Kam

Reputation: 6008

memory layout in multiple inheritance

#include <iostream>
using namespace std;

struct Left
{
   char i = 'k';
};

struct Right
{
   int a = 99;
};

class Bottom : public Left, public Right
{};

int main()
{
    Bottom b;

    Left l = b;
    cout << l.i;

    Right r = b;
    cout << r.a;

    return 0;    
}
// output
// k99

How did this work?

if the memory layout of Bottom is:

Left
Right
Bottom

Then slicing b (i.e. Bottom) to Left object, should be ok, but how can it work when I slice Bottom to Right object?

Note: all this would be ok if I used casting. But I did not.

Upvotes: 3

Views: 1869

Answers (1)

Christophe
Christophe

Reputation: 73366

The Bottom to Right or to Left is a proper conversion, not just a slicing. The compiler generates code using the correct offset of the sub-object in Bottom.

This Dr.Dobbs article should be of interest to you.

Upvotes: 3

Related Questions