This question has already been answered:

Good day.
There is a conditional class

class Class1 { public: Class1() : m_foo(5) { } ~Class1(); int m_foo = 3; }; 

In the case of creating a Class1 my_class1; object Class1 my_class1; how many times will m_foo be initialized?

Reported as a duplicate member of AnT c ++ Feb 14 '18 at 22:27 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • It is almost always better to initialize only in the constructor - AR Hovsepyan
  • @ARHovsepyan the better? - αλεχολυτ

2 answers 2

An example from the standard of the language of clause 12.6.2 / 9 (by the way, the question relates to c ++ 11 and has not changed in c ++ 14):

If you ’ve been given the data, you ’ve been ignored. [Example: Given

 struct A { int i = /∗ some integer expression with side effects ∗/ ; A(int arg) : i(arg) { } // ... }; 

It is a design that will make it easy to make it . —End example]

Translating into Russian: If a non-static data member has as an initializer directly in the class definition (via = or {} ), i.e. brace-or-equal-initializer , and the member initializer in the constructor initializer , i.e. mem-initializer , then only initialization will be performed in the constructor. Initialization directly in the class will be ignored. This rule applies to the delegation of constructors (indirect initialization).

Additionally, I want to note that initialization, by definition, can be done no more than once, changing the value of a variable in the future is already an assignment.

  • Yes, you are right on terminology and thanks for the detailed answer. - goldstar_labs

Once, value 5. The value 3 is for a constructor case in which you do not initialize m_foo .

  • Those. For each of the constructors, a code will be created that chooses a value either from the declaration (int m_foo = 3;) or from the constructor (m_foo (5))? - goldstar_labs