At what point in time during execution will int intr = 5 be assigned?

class B { private: int a = 5; public: B(); ~B(); } 
  • To understand how it actually works, it is useful to look at the assembler code generated by the https://gcc.godbolt.org/ compiler. You do not need to understand it thoroughly, but it will help to understand the order of calling functions and other operations (not forgetting about UB). - free_ze
  • 2
    @free_ze: Premature throwing into looking at the assembler code usually gives rise to unfounded speculation, which have no relation to the real semantics of the language. First, it makes sense to study at least the basics of the theory so that it is clear what the compiler is trying to implement. - AnT 5:26 pm
  • @AnT, of course, all this is only based on the Standard. Assembly listings are only a tool; if applied with the head, “prematurity” will only benefit. - free_ze

1 answer 1

This is no "assignment". This is the initializer and it will be used to initialize B::a , not assignment. The alternative (and equivalent) record form will be

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

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

 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 can explicitly initialize B::a , and some can not do explicit initialization for B::a . In the latter case, your 5 will enter

 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 only to constructors. They are also taken into account in the “constructorless” initialization forms. For example, if a class is an aggregate and is initialized using aggregate initialization , such initializers are also taken into account by the compiler.

 struct S { int x; int y = 42; int z; }; ... S s = { 5 }; // Агрегатная инициализация // Здесь `sx` равно 5, `sy` равно 42, `sz` равно 0 
  • one
    Everything, now it became clear how it works and what is needed, thank you! - maxim
  • @maxim, then accept the answer by clicking on the check mark to the left of it. - Qwertiy