4
votes

The C++ standard says (8.5/5):

To default-initialize an object of type T means:

  • If T is a non-POD class type (clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor).

  • If T is an array type, each element is default-initialized.

  • Otherwise, the object is zero-initialized.

With this code

struct Int { int i; };

int main()
{
    Int a;
}

the object a is default-initialized, but clearly a.i is not necessarily equal to 0 . Doesn't that contradict the standard, as Int is POD and is not an array ?

Edit Changed from class to struct so that Int is a POD.

3
"clearly a.i is not necessarily equal to 0" why? "Otherwise, the object is zero-initialized.".Viruzzo
You are reading an outdated spec. in the most recent spec, default initialization will leave you values uninitializedJohannes Schaub - litb
@JohannesSchaub-litb Could you show the updated text on this ?Belloc

3 Answers

6
votes

From 8.5.9 of the 2003 standard:

If no initializer is specified for an object, and the object is of (possibly cv-qualified) non-POD class type (or array thereof), the object shall be default-initialized; if the object is of const-qualified type, the underlying class type shall have a user-declared default constructor. Otherwise, if no initializer is specified for a nonstatic object, the object and its subobjects, if any, have an indeterminate initial value); if the object or any of its subobjects are of const-qualified type, the program is ill-formed.

The class you show is a POD, so the highlighted part applies, and your object will not be initialized at all (so section 8.5/5, which you quote, does not apply at all).

Edit: As per your comment, here the quote from section 8.5/5 of the final working draft of the current standard (I don't have the real standard, but the FDIS is supposedly very close):

To default-initialize an object of type T means:

— if T is a (possibly cv-qualified) class type (Clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);

— if T is an array type, each element is default-initialized;

otherwise, no initialization is performed.

1
votes

Your variable is not initialized. Use

Int a = Int();

to initialize your POD or declare a standard constructor to make it non POD; But you can also use your POD uninitialized for performance reasons like:

Int a;
a.i = 5;
0
votes

No, the object a is not default-initialized. If you want to default-initialize it, you have to say:

Int a = Int() ;