As the order of initialisation is dependent on the order they are defined in your class, the member order is ignored: C++: Initialization Order of Class Data Members.
So I would just move the integer and string above MyOb1
and MyOb2
, also @Matt McNabb also pointed out that you should use the params passed in your constructor in the initialisation of your MyOb1/2 objects to avoid ambiguity (a sensible suggestion):
class MyClass
{
private:
int i;
std::string str;
MyOb1 Obj1;
MyOb2 Obj2;
public:
MyClass(int iIn, const std::string& strIn)
: i(iIn), // here
str(strIn),
Obj1(iIn),
Obj2(iIn, strIn) {}
}
To quote from the standard section 12.6.2 (the latest draft has this on page 266):
5 Initialization shall proceed in the following order:
— First, and only for the constructor of the most derived class as
described below, virtual base classes shall be initialized in the
order they appear on a depth-first left-to-right traversal of the
directed acyclic graph of base classes, where “left-to-right” is the
order of appearance of the base class names in the derived class
base-specifier-list.
— Then, direct base classes shall be initialized in declaration order
as they appear in the base-specifier-list (regardless of the order of
the mem-initializers).
— Then, nonstatic data members shall be initialized in the order they
were declared in the class definition (again regardless of the order
of the mem-initializers).
— Finally, the body of the constructor is executed. [Note: the
declaration order is mandated to ensure that base and member
subobjects are destroyed in the reverse order of initialization. ]