Default initialization in C++

Only foo3 will be in all contexts. foo2 and foo will be if they are of static duration. Note that objects of type Foo may be zero initialized in other contexts:

Foo* foo = new Foo(); // will initialize bar to 0
Foo* foox = new Foo; // will not initialize bar to 0

while Foo2 will not:

Foo2* foo = new Foo2(); // will not initialize bar to 0
Foo2* foox = new Foo2; // will not initialize bar to 0

that area is tricky, the wording as changed between C++98 and C++03 and, IIRC, again with C++0X, so I'd not depend on it.

With

struct Foo4
{
   int bar;
   Foo4() : bar() {}
};

bar will always be initialized as well.


Since bar is a built-in type its default initialization will be undefined for Foo1 and Foo2. If it would have been a custom type, then the default constructor would have been called, but here it's not the case.

Lesson: always initialize your variables.