Mr.Pricky
Mr.Pricky

Reputation: 37

sizeof on class with multiple inheritance

First of all, I know sizeof depends on machine and compiler implementation. I am using Windows 8.1. x64, gcc 5.3.0., no flags are passed to the compiler.
I have the following code from my university lecture:

#include <iostream>
class A
{
    public:
        int a;
        int b;
        A(){ a = 1; b = 2; }
};

class S1 : public A {
    public:
        int x1;
        S1(){ x1 = 5;}
};

class S2 : public A {
    public:
        int x2;
        S2(){ x2 = 6;}
};

class S12 : public S1, public S2 {
    public:
       int x12;
       S12(){ x12 = 7;}
};

int main()
{
    std::cout << "S1: " << sizeof(A) << std::endl;
    std::cout << "S1: " << sizeof(S1) << std::endl;
    std::cout << "S2: " << sizeof(S2) << std::endl; 
    std::cout << "S12: " << sizeof(S12) << std::endl;
}

On my machine, I got the following output:
S1: 8
S1: 12
S2: 12
S12: 28

I can understand why S1 is 8 and S1,S2 are 12 bytes, but I don`t understand why S12 is 28 - I expect it to be 20, because it must have 5 integer variables (4 bytes each).
Why is S12 28 bytes?

Upvotes: 3

Views: 290

Answers (1)

There are 7 integers in your class

S1::A::a
S1::A::b
S1::x1
S2::A::a
S2::A::b
S2::x2
x12

S12 contains two A objects. If you want only one A object, you need to inherit virtually from it:

#include <iostream>    

struct A { int a = 1; int b = 2; };
struct S1 : virtual A { int x1 = 5; };
struct S2 : virtual A { int x2 = 6; };
struct S12 : S1, S2 { int x12 = 7; };
int main()
{
    std::cout << "A: " << sizeof(A) << std::endl;
    std::cout << "S1: " << sizeof(S1) << std::endl;
    std::cout << "S2: " << sizeof(S2) << std::endl; 
    std::cout << "S12: " << sizeof(S12) << std::endl;
}

The result you get will be much more implementation dependant than before - virtual base classes are tricky, and different compilers tend to use different implementation techniques for them. I get:

A: 8
S1: 24
S2: 24
S12: 40

Upvotes: 5

Related Questions