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
c ++ inheritance constructor sizeof
Byteme95
source share