c++ – Assignment in class description

Question:

At what point in time during execution will the assignment of int a = 5 occur?

class B {
private:
   int a = 5;
public:
   B();
   ~B();
}

Answer:

This is no "assignment". This is an initializer and will be used to initialize B::a , not to assign. An alternative (and equivalent) notation would be

class B {
  ...
  int a{ 5 };
  ...
};

This initializer will be used to default initialize this class member in the constructors of this class. If you "forget" to explicitly initialize B::a in class B 's constructor initialization list

B::B() // Инициализация для `a` отсутствует
  {}

then B::a will be implicitly initialized to 5 . As if someone quietly wrote for you

B::B() : a(5) 
  {}

If you yourself explicitly initialize B::a in the constructor

B::B() : a(42) 
  {}

then the initializer 5 you specified above will simply be ignored.

You can have many different constructors in class B Some of them may explicitly initialize B::a , and some may not explicitly initialize B::a . In the latter case, your 5

class B 
{
private:
   int a = 5;
public:
   B(int) : a(42) // Здесь есть явная инициализация `a`
   {
     // Здесь `a` равно 42
   }

   B(double)      // Здесь нет явной инициализации `a`
   {
     // Здесь `a` равно 5
   }
};

The functionality of such initializers is not limited to constructors. They are also taken into account in "non-constructor" forms of initialization. For example, if the class is an aggregate and is initialized using aggregate initialization , then such initializers are also taken into account by the compiler

struct S
{
  int x;
  int y = 42;
  int z;
};
...
S s = { 5 }; // Агрегатная инициализация 
// Здесь `s.x` равно 5, `s.y` равно 42, `s.z` равно 0
Scroll to Top