Order of calling base class constructor from derived class initialization list

Solution 1:

The order you refer in your question is not the "order of calling base constructor". In fact, you can't call a constructor. Constructors are not callable by the user. Only compiler can call constructors.

What you can do is to specify initializers. In this case (constructor initializer list) you are specifying initializers for subobjects of some larger object. The order in which you specify these initializers does not matter: the compiler will call the constructors in a very specific order defined by the language specification, regardless of the order in which you specify the initializers. The base class constructors are always called first (in the order in which the base classes are listed in class definition), then the constructors of member subobjects are called (again, in the order in which these members are listed in the class definition).

(There are some peculiarities in this rule when it comes to virtual base classes, but I decided not to include them here.)

As for the bad behaviors... Of course there is a potential for "bad behaviors" here. If you assume that the order of initialization depends on the order you used in the constructor initializer list, you will most likely eventually run into an unpleasant surprise, when you discover that the compiler completely ignores that order and uses its own order (the order of declaration) instead. For example, the author of this code

struct S {
  int b, a;
  S() : a(5), b(a) {}
};

might expect a to be initialized first, and b to receive the initial value of 5 from a, but in reality this won't happen since b is initialized before a.

Solution 2:

The order is well defined. It does not depend on how you specify them while initializtion.
Base class constructor B will be called first and then the member variables(d1 & d2) in the order in which they are declared.

To explain the comment in @Andrey T's answer.

class MyClass1: public MyClass2, public virtual MyClass3
{


};

The order of calling the Base class constructors is well defined by the standard and will be:

MyClass3  
MyClass2
MyClass1

The virtual Base class MyClass3 is given preference over Base Class MyClass2.

Solution 3:

The order things appear in the initialisation list is not significant. In your case, the base object will always be initialised first, followed by d1 and d2, in that order. Initialisation is performed in order of derivation and in order members appear in the class definition.

Having said that, it is normally considered good style to write the initialisation list in the order of initialisation, and some compilers will issue a warning if you don't do this.