C++ – Initialization Order of Inheritance or Class Members

What do you expect to be the values of  A::c ,  A::b  and   myglobal  in the end of the main function?

The values will be:

  •   A::c = undefined
  •   A::b = 10
  •   myglobal = 1

The initialization order will be the following:

  1. Parent class C  in A  constructor.
  2. Parent class B  in A  constructor.
  3. Member c   in A .
  4. 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.

Tags

Categories

Meta

Peter Merkert Written by:

Be First to Comment

Leave a Reply