0

Haven't found quite this problem in the site. So say I have two classes, one which holds a reference to the other:

class ClassA {};

class ClassB
{
    classA & r_classA;
    public:
        ClassB( ClassA & io_classA ):r_classA( io_classA ){}
};

So, if I want to create an instance of ClassB, i have to pass it a reference to classA in the constructor:

int main()
{
    ClassA classA;
    ClassB classB ( classA );
    return 0;
}

Now say I create a class ClassC that holds these two:

class ClassC
{
    ClassA m_classA;
    ClassB m_classB;
    public:
        ClassC();
}

My question is, can I count on m_classA being created before m_classB is constructed in the initialization list? That is to say, can I do this:

ClassC::ClassC()
: m_classA()
, m_classB( m_classA )
{}

Is this standards compliant? Portable? Do I need to take any special precautions? I'm declaring m_classA before m_classB in the body of ClassC already, and the compiler didn't throw any warnings. The program seems to work ok. I just want to check that I'm not counting on some unreliable behavior that'll cause a crash or weird bugs down the line.

Kian
  • 1,654
  • 1
  • 14
  • 22
  • 2
    Seems to me that this is a duplicate of http://stackoverflow.com/questions/1242830/constructor-initialization-list-evaluation-order . – us2012 Oct 05 '13 at 19:52

1 Answers1

5

Class members are initialized in their order of declaration, so your code is well-defined and does what you think.

(A good compiler should warn you if the order of the constructor initializer list differs from the order of declaration, since this is indeed a subtle source of errors. But your code does it correctly.)

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084