c++c++11initializationuniform-initializationdirect-initialization

Initialization in C++


What is the difference between direct initialization and uniform initialization in C++?

What is the difference between writing

int a{5}; // Uniform

and

int a(5); // Direct

Solution

  • In this particular example there will be no difference due to the type and the value choosen: int and 5.

    In some other cases what initialization means does depend on whether we use {} or (). When we use parenthesis, we're saying that the values we supply are to be used to construct the object, making a computation. When we use curly braces, we're saying that (if possible) we want to list initialize the object; If it is not possible to list initialize the object, the object will be initialized by other means.

    E.g.

    // a has one element, string "foo"
    vector<string> a{"foo"};
    // error, cannot construct a vector from a string literal
    vector<string> b("foo");
    // c has 21 default initialized elements
    vector<string> c{21};
    // d has 21 elements with value "foo"
    vector<string> d{21, "foo"};
    

    For a built-in type, such as int, the {} will have another function:

    double d = 3.14;
    int i = 0;
    i = {d};
    // error: narrowing conversion of ‘d’ from ‘double’ to ‘int’
    

    For more information you may check the cppreference.com - Initialization