Sizeof by class with multiple inheritance

First of all, I know that sizeof is machine and compiler implementation dependent. 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 is 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). <w> Why S12 28 bytes?

+3


source to share


1 answer


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 objects A

. If you only need one object A

, you need to inherit practically 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 will get will be much more implementation dependent than before - virtual base classes are complex and different compilers tend to use different implementation methods for them. I get:

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

      

+5


source







All Articles