What causes difference of size of structs between inheritance and member?

Viewed 75

I cannot understand the reason for difference in size of C and C2 in the following code:

#include <iostream>

struct A {
    int* x;
};

struct B {
    A a;
    int y;
};

struct C : B {
   int z;
};

struct B2 : A {
   int y;
};

struct C2 : B2 {
   int z;
};
    
int main()
{
    std::cout << sizeof(A) << std::endl; // 8
    std::cout << sizeof(B) << std::endl; // 16
    std::cout << sizeof(C) << std::endl; // 24
    std::cout << sizeof(B2) << std::endl; // 16
    std::cout << sizeof(C2) << std::endl; // 16
}

https://wandbox.org/permlink/GEWj2LQxloC34lNS

What I (probably) understand is that,

  • C has the following memory layout
|0      |4      |8      |12     |16      |20     |
|A::x-----------|B::y---|padding|C::z----|padding|
  • C2 has the following memory layout.
|0      |4      |8      |12      |
|A::x-----------|B::y---|C::z----|

In C, it seems that the padding of structure B remains, but in C2, it seems that the padding of structure B2 is packed. What is the cause of this difference? (Is it defined in the C++ standard? What kind of rule is it?)

1 Answers

C++ allows subobjects introduced in a derived class to overlap (padding in) base subobjects as long as those objects are not standard-layout. It does not allow any overlap between member subobjects, or overlap of a standard-layout base subobject.

Look at the size and layout of struct B to understand why struct C has internal padding.

Related