Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is second initialization allowed in C++11

Under C++11 it is possible to initialize class members directly upon declaration. But it is also ok to initialize them once more in the initialization list of the constructor... why?

#include <iostream>



struct MyStr
{

    MyStr()
    :j(0)
    {
        std::cout << "j is " << j << std::endl; // prints "j is 0"
    }

    const int j = 1;

};

int main()
{
    const int i = 0;

    MyStr mstr; 
}

Because doing something like this is an error, understandably:

MyStr()
:j(0),
j(1)
{
}

What is different about the first example, where the data member gets initialized upon declaration and then again in the constructor's init list?

like image 681
lo tolmencre Avatar asked Sep 14 '15 21:09

lo tolmencre


2 Answers

Only one initialization actually happens. It's just that you're allowed to write a "default" one in the form of the brace-or-equals initializer, but if your constructor initializer list specifies an initializer, too, that one is the only one that's used.

As a side note, as of C++14, a brace-or-equals initializer can be provided for a non-static data member of an aggregate (which cannot have constructors).

like image 52
Kerrek SB Avatar answered Oct 11 '22 09:10

Kerrek SB


So that an individual constructor may override it.

From the original feature proposal:

It may happen that a data member will usually have a particular value, but a few specialized constructors will need to be cognizant of that value. If a constructor initializes a particular member explicitly, the constructor initialization overrides the member initializations as shown below: [..]

Remember, you can have more than one constructor.

like image 41
Lightness Races in Orbit Avatar answered Oct 11 '22 09:10

Lightness Races in Orbit