简体   繁体   中英

Why are member classes initialized first in C++?

I have tried the ff. code:

#include <iostream>
struct A
{
    A() { std::cout << "1"; }
    A(const A&) { std::cout << "2"; }
    A(A&&) { std::cout << "3"; }
};

struct B
{
    B() { std::cout << "4"; }
    B(const B& b) : a(b.a) { std::cout << "5"; }
    B(B&& b) : a(b.a) { std::cout << "6"; }
    A a;
};

int main()
{
    B b1;
    std::cout << "END OF b1" << std::endl;
    B b2 = std::move(b1);
}

And the output is:

14END OF b1
26

I was just wondering why that is the behavior, how come the constructor of B is called second? I've also tried to use class instead of struct and it's the same behavior.

This is expected behavior. The initialization order is specified as

1) If the constructor is for the most-derived class, virtual base classes are initialized in the order in which they appear in depth-first left-to-right traversal of the base class declarations (left-to-right refers to the appearance in base-specifier lists)

2) Then, direct base classes are initialized in left-to-right order as they appear in this class's base-specifier list

3) Then, non-static data members are initialized in order of declaration in the class definition.

4) Finally, the body of the constructor is executed

Then the data member a is always initialized (step #3) before the execution of the constructor of B (step #4).

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