Search code examples
c++initialization-list

Initializer lists with internal references


I would like to use an initializer lists for object initialization to simplify object management, but the issue is that objects reference each other.

//B::B(A &a) //The only available constructor for B

class AB
{
    A m_a;
    B m_b;

    AB()
        : m_a()
        , m_b(m_a)

    ...
};

Is this allowed by standard? From what I understand, it should be, given that member declaration within class are A, then B, order in initialization list doesn't matter, as they will be initialized by their physical order within class.


Solution

  • Is this allowed by standard? From what I understand, it should be, given that member declaration within class are A, then B, order in initialization list doesn't matter, as they will be initialized by their physical order within class.

    Yes, the order of initialization is that of the declaration of the member attributes in the class. Additionally, and depending on what B constructor does, it is correct (although close to the edge) to pass a reference to a yet uninitialized object as long as the reference (or pointer) as long as the reference or pointer is stored, but the object not used.