views:

99

answers:

1

This is a problem I come across often. The following examples illustrates it:

struct A {
    int m_SomeNumber;
};

struct B {
    B( A & RequiredObject );
private:
    A & m_RequiredObject;
};

struct C {
    C( );
private:
    A m_ObjectA;
    B m_ObjectB;
};

The implementation of the constructor of C looks something like this:

C::C( )
 : B( m_ObjectA )
{ }

Since the order of initialization is not defined, m_ObjectA might be uninitialized when the constructor of m_ObjectB is called, resulting in undefined behavior. One way to force a certain order of initialization would be to make the members pointers and initialize them in the constructor body, thus forcing the correct order, but this is ugly for several reasons. Is there any way to force a certain initializtion order using the initialization-list of the constructor? If not, do you have any other suggestions how to handle this.

+10  A: 

Since the order of initialization is not defined

On the contrary, it is well-defined. The order of initialization is equal to the order in which the member variables are declared in your class (and that’s regardless of the actual order of the initialization list! It’s therefore a good idea to let the initialization list order match the order of the declarations to avoid nasty surprises).

Konrad Rudolph
well, I thought otherwise. Thanks for the quick answer!
Space_C0wb0y
I'd add that this is quite brittle, as your reliance on ordering may be nonobvious to the reader. So at least I'd add a comment to the definition of m_objectB to the effect of "must be defined after m_objectA".
peterchen
@peterchen: that’s why the order of the initialization list should really match the declaration order.
Konrad Rudolph
I would also add the appropriate compiler option to warn you. In g++ it is '-Wreorder' to force the user provided initialization list order to match the order of definition of the member attributes.
David Rodríguez - dribeas
@David - very useful. Anyone knows if the MS compiler has something similar?
Manuel
Does something like this also apply for the destruction-order (my intuition would be the reverse)?
Space_C0wb0y
@Space_C0wb0y: yes, exactly. Destruction happens in exactly the reverse order of construction, and this too is well-defined.
Konrad Rudolph