14

Possible Duplicate:
What do the following phrases mean in C++: zero-, default- and value-initialization?

I was reading this answer, so I came across the second word : value-initialize. Initially I thought this is same as default-initialize but the context hints me that I'm wrong.

So my question is :

What is the difference between default-initialize and value-initialize?

I would like to understand the difference with some examples.

Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • Possible duplicate of [What do the following phrases mean in C++: zero-, default- and value-initialization?](http://stackoverflow.com/questions/1613341/what-do-the-following-phrases-mean-in-c-zero-default-and-value-initializati) – Xeo Apr 10 '11 at 08:43

2 Answers2

10

According to the standard (8.5/4,5):

To default-initialize an object of type T means:
— if T is a non-POD class type 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.


To value-initialize an object of type T means:
— if T is a class type (clause 9) with a user-declared constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
— if T is a non-union class type without a user-declared constructor, then every non-static data member and base-class component of T is value-initialized;96)
— if T is an array type, then each element is value-initialized;
— otherwise, the object is zero-initialized

Karl von Moor
  • 8,484
  • 4
  • 40
  • 52
  • 2
    Warning: This answer is out-of-date for C++11. See http://stackoverflow.com/q/22233148/368896. In C++11, for the `default-initialize` case, the `-- otherwise, the object is zero-initialized` is replaced by `-- otherwise, no initialization is performed`. – Dan Nissenbaum Jul 05 '15 at 17:20
9

"default-initialise" gives it the default value as specified by the standard, which could be garbage.

"value-initialise" initialises it to a specific value - one set in the constructor, for instance, or optimised by the compiler.

Ben Stott
  • 2,218
  • 17
  • 23
  • 1
    This helps me remember that when you `value` initialize something, the thing really is getting its VALUES set (even if that means setting them to 0 as a fall-through if no constructor is available), whereas plain old `default` initialization will have no fall-through and values can be uninitialized if no constructor sets their value. In the spirit of C++, there must be some condition to force the `value` initialization - i.e., you must explicitly pass parentheses, as in `A a();` (see http://stackoverflow.com/a/8860787/368896). – Dan Nissenbaum Jul 05 '15 at 17:24
  • 1
    @Dan Nissenbaum Isn't A a(); a vexing parse issue? Seen as a function declaration? – Zebrafish Dec 22 '16 at 08:39