At what point in time during execution will int intr = 5 be assigned?
class B { private: int a = 5; public: B(); ~B(); } At what point in time during execution will int intr = 5 be assigned?
class B { private: int a = 5; public: B(); ~B(); } 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 Source: https://ru.stackoverflow.com/questions/778300/
All Articles