Adding a default constructor to the base class changes the sizeof () derived type

I tend to think that I have a pretty good idea of ​​C ++ internal functions and memory layouts, but it puzzled me. I have the following test code:

#include <stdio.h> struct Foo { //Foo() {} int x; char y; }; struct Bar : public Foo { char z[3]; }; int main() { printf( "Foo: %u Bar: %u\n", (unsigned)sizeof( Foo ), (unsigned)sizeof( Bar ) ); } 

The conclusion is reasonable:

Foo: 8 Bar: 12

However, this is a very strange part, if I uncomment this simple default constructor to Foo (), the size is changed (Bar)! How can adding ctor change the memory locations of these classes?

Foo: 8 Bar: 8

Compiled using gcc-7.2

+8
c ++ inheritance constructor sizeof
source share
1 answer

GCC follows Itanium ABI for C ++, which prevents the addition of a POD tail to store data elements of a derived class.

Adding a user-created constructor means that Foo no longer a POD, so the restriction does not apply to Bar .

See this question in ABI for more details .

+3
source share

All Articles