Search code examples
c++constructorctor-initializer

in C++, how should I enforce the order of composited object constructors in an initializer list when they have dependencies


If I have a class that composit other objects that have inter-dependencies, (how) should I enforce their construction order?

E.g.

class Parent
{
    Child1 c1;
    Child2 c2;
};

Imagine the constructor of Child2 requires a Child1& and I want to pass in c1 to the c2 constructors.

If I just do the following...

Parent::Parent()
    : c2(c1)
{
}

...this may not be good thing as c1 may not be constructed by the time the initializer for c2 is run? Or is it good enough that c1 comes before c2 in the class declaration?

Or should I explicitly refer the c1 constructor (if that is not neccessary, then is it a good practice to do so to make it explicit?). E.g.

class Parent
{
    Child1 c1;
    Child2 c2;
};

Parent::Parent()
    : c1()
    : c2(c1)
{
}

Solution

  • Members are always constructed in the order that they are declared. So if you have:

    class Parent
    {
        Child1 c1;
        Child2 c2;
    };
    

    you are guaranteed that c1 will be constructed before c2. So, if c2 needs a Child1&, then this is perfectly well-defined:

    Parent::Parent()
        : c2(c1)
    {
    }
    

    c1 will be default-constructed, and then c2 will be constructed with a definitely-already-constructed c1.