Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C++11 re-initialize initialized member fields?

Tags:

c++

c++11

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?

like image 718
Rafid Avatar asked Nov 09 '13 14:11

Rafid


People also ask

Are variables in C automatically initialized?

There's no automatic initialization of automatic ( local in your parlance) variables in C.

Does C++ initialize member variables?

Member variables are always initialized in the order they are declared in the class definition.

Should member variables be initialized?

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.

Does C initialize variables to zero?

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).


1 Answers

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.

like image 113
jogojapan Avatar answered Sep 27 '22 16:09

jogojapan