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?)