Does the default constructor initialize built-in types?
Implicitly defined (by the compiler) default constructor of a class does not initialize members of built-in types.
However, you have to keep in mind that in some cases the initialization of a instance of the class can be performed by other means. Not by default constructor, nor by constructor at all.
For example, there's a widespread incorrect belief that for class C
the syntax C()
always invokes default constructor. In reality though, the syntax C()
performs so called value-initialization of the class instance. It will only invoke the default constructor if it is user-declared. (That's in C++03. In C++98 - only if the class is non-POD). If the class has no user-declared constructor, then the C()
will not call the compiler-provided default constructor, but rather will perform a special kind of initialization that does not involve the constructor of C
at all. Instead, it will directly value-initialize every member of the class. For built-in types it results in zero-initialization.
For example, if your class has no user-declared constructor
class C {
public:
int x;
};
then the compiler will implicitly provide one. The compiler-provided constructor will do nothing, meaning that it will not initialize C::x
C c; // Compiler-provided default constructor is used
// Here `c.x` contains garbage
Nevertheless, the following initializations will zero-initialize x
because they use the explicit ()
initializer
C c = C(); // Does not use default constructor for `C()` part
// Uses value-initialization feature instead
assert(c.x == 0);
C *pc = new C(); // Does not use default constructor for `C()` part
// Uses value-initialization feature instead
assert(pc->x == 0);
The behavior of ()
initializer is different in some respects between C++98 and C++03, but not in this case. For the above class C
it will be the same: ()
initializer performs zero initialization of C::x
.
Another example of initialization that is performed without involving constructor is, of course, aggregate initialization
C c = {}; // Does not use any `C` constructors at all. Same as C c{}; in C++11.
assert(c.x == 0);
C d{}; // C++11 style aggregate initialization.
assert(d.x == 0);
I'm not quite certain what you mean, but:
struct A { int x; };
int a; // a is initialized to 0
A b; // b.x is initialized to 0
int main() {
int c; // c is not initialized
int d = int(); // d is initialized to 0
A e; // e.x is not initialized
A f = A(); // f.x is initialized to 0
}
In each case where I say "not initialized" - you might find that your compiler gives it a consistent value, but the standard doesn't require it.
A lot of hand-waving gets thrown around, including by me, about how built-in types "in effect" have a default constructor. Actually default initialization and value initialization are defined terms in the standard, which personally I have to look up every time. Only classes are defined in the standard to have an implicit default constructor.