What do you expect to be the values of A::c , A::b and myglobal in the end of the main function?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
int myglobal = 0; class B { public: B::B() { myglobal = 1; } }; class C { public: C::C() { myglobal = 2; } }; class A : public C, public B { public: A() : B(), C(), b(10), c(b) { } int c; const int b; }; int main() {A a;}; |
The values will be:
- A::c = undefined
- A::b = 10
- myglobal = 1
The initialization order will be the following:
- Parent class C in A constructor.
- Parent class B in A constructor.
- Member c in A .
- Member b in A .
Why?
For the inheritance, the order of the inheritance in the class definition of class A is important. It says class A : public C, public B , which defines the order that C that is initialized first and B second.
For the member variables, the order of definition within the class matters. As c is defined before b , c is initialized earlier. When executing the program, b is uninitialized when c is initialized. Thence, the value of c is unknown after its’ initialzation.
So, the order of the initialization order in A() : B(), C(), b(10), c(b) does not matter.
Be First to Comment