default initialization

< cpp‎ | language
Revision as of 07:01, 5 December 2013 by Cubbi (Talk | contribs)

Provides the default initial value to a new object.



T object ; (1)
new T ; (2)


Default initialization is performed in three situations:

1) when a variable with automatic storage duration is declared with no initializer
2) when an object with dynamic storage duration is created by a new-expression without an initializer
3) when a base class or a non-static data member is not mentioned in a constructor initializer list and that constructor is called.

The effects of default initialization are:

  • If T is a class type, the default constructor is called to provide the initial value for the new object.
  • If T is an array type, every element of the array is default-initialized.
  • Otherwise, nothing is done.

If T is a const-qualified type, it must be a class type with a user-provided default constructor.


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)

Reference cannot be default-initialized.


#include <string>
struct T1 {};
class T2 { 
    int mem;
    T2() {} // "mem" not in initializer list
int n; // This is not default-initialization, the value is zero.
int main()
    int n;            // non-class: the value is undeterminate
    std::string s;    // calls default ctor, the value is "" (empty string)
    std::string a[2]; // calls default ctor, creates two empty strings
//    int& r;         // error: default-initializing a reference
//    const int n;    // error: const non-class type
//    const T1 nd;    // error: const class type with implicit ctor
    T1 t1; // ok, calls implicit default ctor
    const T2 t2; // ok, calls the user-provided default ctor 
                 // t2.mem is default-initialized (to indeterminate value)

See also