简体   繁体   中英

Can I initialize an object in the initialization list with another class member?

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.

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM