#pragma pack(push, 4)
class Father
{
public:
int b;
char c;
};
class Child : public Father
{
char e;
};
#pragma pack(pop)
sizeof(Father)=8
sizeof(Child)=12
But if We change class Father like this:
class Father
{
private:// change from public
int b;
char c;
};
sizeof(Child)=8
It's an implementation detail of the compiler. In other words, not really your business, unless you really, really need to make your data as small as possible. Beware premature optimization here.
In the end, it probably comes down to peculiarities of the Common C++ ABI, using terms like "POD for the purpose of layout" and "base class padding reuse".
Edit: Or not, because those pragmas suggest you're using Visual Studio. In that case, never forget that the MS ABI is a jungle of wild backwards compatibility hacks.
The difference in size you are seeing is a result of the compatibility to C. C only knows about struct
where everything is public. So, when you use public
members in a C++ struct
or class
, the ABI is compatible with C, hence it needs to follow the alignment rules of C.
When you declare the members private
, the C++ ABI has more freedom to optimize the packing of the members.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With