These are the definitions of my class:
class Foo{
int _ent;
public:
void printEnt() const{cout << _ent << ' ';}
};
class Bar{
Foo _foo;
public:
void printEnt() const{_foo.printEnt();}
};
And this is my test code:
char* buf = new char[sizeof(Foo) + sizeof(Foo) + sizeof(Bar)];
fill(buf, buf + sizeof(Foo) + sizeof(Foo) + sizeof(Bar), 'J');
cout << ((int*)buf)[0] << ' ' << ((int*)buf)[1] << ' ' << ((int*)buf)[2] << endl;
Foo* first = new (buf) Foo;
Foo* second = new (buf + sizeof(Foo)) Foo();
Bar* third = new (buf + sizeof(Foo) * 2) Bar;
first->printEnt(); second->printEnt(); third->printEnt();
My conclusion:
1246382666 1246382666 1246382666
1246382666 0 1246382666
But if I add publicthe default ctor to Foo:Foo() : _ent(0) {}
My conclusion will be:
1246382666 1246382666 1246382666
0 0 0
Is this the right behavior? Should adding my own default ctor remove the default initialization capability?
I run this code on gcc 4.8.1, if that matters. The results must be reliable, because I run debugging and state:assert(sizeof(Foo) == sizeof(int) && sizeof(Bar) == sizeof(int));
source
share