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?
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With