C++11 now supports setting the value of a class member field at declaration time, like this:
class MyClass
{
private
int test = 0;
}
If I also initialize the variable in the constructor like this:
class MyClass
{
private
int test = 0;
public:
MyClass() : test(1)
{
}
}
will this cause the variable to have its value set twice, or the specification dictates that the compiler should optimise this to initialize the variable only once? If the specification doesn't dictate anything, do you know the behaviour of the famous compilers (e.g. MSVC, GCC, etc.) with respect to this?
There's no automatic initialization of automatic ( local in your parlance) variables in C.
Member variables are always initialized in the order they are declared in the class definition.
You should always initialize native variables, especially if they are class member variables. Class variables, on the other hand, should have a constructor defined that will initialize its state properly, so you do not always have to initialize them.
There's no need to initialize them, as the C standard requires global, uninitialized variables to be implicitly initialized to zero or NULL (no matter whether they are static or exported).
The Standard actually has a rule for this, in §12.6.2/9:
If a given non-static data member has both a brace-or-equal-initializer and a mem-initializer, the initialization specified by the mem-initializer is performed, and the non-static data member’s brace-or-equal-initializer is ignored. [ Example: Given
struct A { int i = /∗ some integer expression with side effects ∗/ ; A(int arg) : i(arg) { } // ... };
the A(int) constructor will simply initialize i to the value of arg, and the side effects in i’s brace-or-equal- initializer will not take place. — end example ]
So in the case you described, if the default constructor is called, only the initialization defined there will be performed, and test
will be 1
.
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