45

When I use an initialization list:

struct Struct {
    Struct() : memberVariable() {}
    int memberVariable;
};

the primitive type (int, bool, float, enum, pointer) member variable is default-initialied. Is the value it gets implementation defined or is it the same for all implementations?

sharptooth
  • 167,383
  • 100
  • 513
  • 979

7 Answers7

43

You are not correct. The object is not default-initialized but value-initialized. And its value is well-defined

int = 0, 
bool = false, 
float = 0.0f,  
enum = (enum type)0, 
pointer = null pointer
pointer to member = null member pointer

Note that zero is in the range of values for any enumeration, even if it doesn't contain an explicit enumerator with that vaue, so it's safe to initialize an enumeration variable to that value.

In particular for pointer to data members, the representation used in practice is not all-zero bits. In the so-called C++ Itanium ABI used by at least GCC and Clang, pointer to data members have an all-one bits null representation.

Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
  • Is the object value initialized (and **not** default initialized) because its a non-POD class type? – Prasoon Saurav Sep 27 '10 at 11:24
  • 2
    It's value initialized disregarding the type. `int` is not a non-POD class type. – Johannes Schaub - litb Sep 27 '10 at 11:34
  • 1
    No I was talking about `Struct` as a whole which is a non-POD type of-course. The subobjects are value initialized. – Prasoon Saurav Sep 27 '10 at 11:37
  • @Chubsdad : I have read somewhere that `C++TC1` made explicit that pointers to member are PODs. – Prasoon Saurav Sep 28 '10 at 06:31
  • @JohannesSchaub-litb I am reading C++ primer book, in it mentioned thp at primitive types are default initialized and and the value by which they initialize depends upon where they defined. if inside function then they initialize with `0` and if outside the function then they are undefined. – Abhishek Mane Nov 17 '21 at 07:59
  • @AbhishekMane, In this case we are talking about variables that are members of a user defined type (class, struct). For e.g., see here to understand better about initialization of local variables: https://stackoverflow.com/questions/15212261/default-initialization-of-pod-types-in-c – Hari Aug 24 '22 at 09:32
38

The 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 Thas 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;

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

— otherwise, the object is zero-initialized

.

Is the value it gets implementation defined or is it the same for all implementations?

So the value would be same for all implementations.

Struct is a non-POD type so

 Struct *a =new Struct; // default initialization

 //memberVariable will be initialized to 0 because if T is a non-POD class type
 //the default constructor for T is called 

 Struct *b = new Struct(); //value initializes Struct, which calls the default ctor.

 //memberVariable will be initialized to 0 in this case also.

EDIT :

As @Johannes noticed the primitive type (int, bool, float, enum, pointer) member variable is value-initialized not default initialized.

Community
  • 1
  • 1
Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
  • 1
    Excellent answer. I especially like the reference to the standard. +1 – JoshD Sep 28 '10 at 04:43
  • 3
    The sentence `— otherwise, the object is zero-initialized` in paragraph. 6 `To default-initialize an object of type T means:`is wrong. The correct sentence is `— otherwise, no initialization is performed.` – Belloc Feb 05 '13 at 21:44
  • 2
    This was correct for C++03, but changed as of C++11: the "otherwise" case for default initialization is now "no initialization is performed". – Nate Kohl Aug 18 '13 at 21:19
  • @PrasoonSaurav I am reading C++ primer book, in it mentioned thp at primitive types are default initialized and and the value by which they initialize depends upon where they defined. if inside function then they initialize with 0 and if outside the function then they are undefined. – Abhishek Mane Nov 17 '21 at 07:59
10

For primitive types, default initialisation means that the object is initialised with 0, 0.0 or NULL as appropriate for the type.

Edit: The above is valid for C++98. In C++03, the terms got redefined a bit. Now, using an initialiser of () (which is syntactically only possible for member-objects) results in value initialisation, which for primitive types means that the appropriate value of 0, 0.0 or NULL gets stored.

Bart van Ingen Schenau
  • 15,488
  • 4
  • 32
  • 41
  • Nice, some new usenet guy in here :) Please notice this default-initialisation does not apply to his code (in C++03). – Johannes Schaub - litb Sep 27 '10 at 11:53
  • @Johannes:that is only because the definition of *default initialisation* got changed between C++98 and C++03. In C++03, the `memberVariable` is *value initialised*, with exactly the same effect. – Bart van Ingen Schenau Sep 27 '10 at 12:53
  • 1
    the definition of value initialization differs from the definition of default initialization. If `memerVariable` would be a non-POD without a user declared constructor, default initialization will not initialize its members, while value initialization *will* initialize them. Explaining how default initialization works makes people (including the questioner, who obviously does not know it) believe `memberVariable` is default-initialized, while really it is value initialized. – Johannes Schaub - litb Sep 27 '10 at 13:00
  • @Johannes: Please check the difference between the C++98 and C++03 standards in this respect. The terms have been redefined. – Bart van Ingen Schenau Sep 27 '10 at 14:21
  • 1
    we have had this kind of difference elaborated in length on SO. See http://stackoverflow.com/questions/1613341/what-do-the-following-phrases-mean-in-c-zero-default-and-value-initializati . We have had many [questions and answers](http://stackoverflow.com/search?q=%22value+initialization%22) about this topic, [for example here](http://stackoverflow.com/questions/734958/c-empty-paren-member-initialization-zeroes-out-memory/735007#735007). – Johannes Schaub - litb Sep 27 '10 at 14:39
4

0

If you call () on a primitive, the effect is the same as assigning the default value it would have been given if it had been static.

Jon Hanna
  • 110,372
  • 10
  • 146
  • 251
  • AFAIR, static variables have to be explicitly initialized. Am I mistaken? – DevSolar Sep 27 '10 at 11:45
  • 1
    @DevSolar, "Every object of static storage duration shall be zero-initialized at program startup before any other initialization takes place. [ Note: in some cases, additional initialization is done later. —end note ]" Section 8.5 of a draft copy of the standard I have, item 7. – Jon Hanna Sep 27 '10 at 11:55
  • Does that mean `int foo() { return 0; }` is guaranteed to return `0`? – Aykhan Hagverdili Feb 03 '19 at 18:43
  • @Ayxan it would be, but I'm not seeing how you are seeing these as related. – Jon Hanna Feb 04 '19 at 09:45
  • @JonHanna I meant to say `int foo() { return int(); }`, I am sorry. Is this always `0`? – Aykhan Hagverdili Feb 04 '19 at 10:18
  • 1
    @Ayxan yes. `int()` produces `0` (typed as `int`) and hence it's effectively the same as `return 0;`. – Jon Hanna Feb 04 '19 at 10:58
0

Default initialization of non-class variables with automatic and dynamic storage duration produces objects with indeterminate values (static and thread-local objects get zero initialized)

References and const scalar objects cannot be default-initialized. see below example

#include <string>
 
struct T1 { int mem; };
 
struct T2
{
    int mem;
    T2() { } // "mem" is not in the initializer list
};
 
int n; // static non-class, a two-phase initialization is done:
       // 1) zero initialization initializes n to zero
       // 2) default initialization does nothing, leaving n being zero
 
int main()
{
    int n;            // non-class, the value is indeterminate
    std::string s;    // class, calls default ctor, the value is "" (empty string)
    std::string a[2]; // array, default-initializes the elements, the value is {"", ""}
//  int& r;           // error: a reference
//  const int n;      // error: a const non-class
//  const T1 t1;      // error: const class with implicit default ctor
    T1 t1;            // class, calls implicit default ctor
    const T2 t2;      // const class, calls the user-provided default ctor
                      // t2.mem is default-initialized (to indeterminate value)
}
Ganeshkumar
  • 61
  • 1
  • 10
-1

It depends on how you instantiate a class, if you use ClassName() the POD classes are default initialized to zero for non POD class default constructor is called but if you use ClassName, without the parentheses no default initialization takes place.

yesraaj
  • 46,370
  • 69
  • 194
  • 251
  • 2
    -1. Sorry, but that rule only applies to classes with a compiler-supplied default constructor. Since `Struct::Struct()` is declared, it will be used for both `new Struct` and `new Struct()`. – MSalters Sep 27 '10 at 12:13
-2

Native types like int usually get a garbage value, eg. whatever happens to reside in the memory area it is created in. However this is not defined in the standard, and it might also be initialized to 0, which is quite common in eg. debug builds.

EDIT. But basically, you should never trust an uninitialized variable to hold something specific; Always define the values yourself.

reko_t
  • 55,302
  • 10
  • 87
  • 77