Search code examples
c++constructormultiple-inheritancevirtual-inheritanceorder-of-execution

Virtual base classes order of creation


I have the following problem:

struct A1 {
    A1() { std::cout << "A1, "; }
};

struct A2 {
    A2() { std::cout << "A2, "; }
};

struct AA1 : virtual A1,  A2 {
    AA1() { std::cout << "AA1, "; }
};

struct AA2 : A1, virtual A2 {
    AA2(){ std::cout << "AA2, "; }
};

struct B : AA1, virtual AA2 {
    B() { std::cout << "B "; }
};

int main() {
    B b;
}

When you run this code, the answer is:

A1 A2 A1 AA2 A2 AA1 B

I want to understand where is the first A1 created.

I know the rule that the virtual classes are called before non - virtual classes but that first A1 is the problem that is bothering me.


Solution

  • The first A1 results from the initialization of the (virtual) base of the (non-virtual) base AA1 of B.

    All the virtual bases of B are initialized first, and they are, in order, A1, A2 and AA2. (The initialization of AA2 results in the output A1 AA2.) Then come the direct bases, of which there is only one, AA1 (whose initialization prints A2 AA1), and finally the class itself, printing B. All the virtual bases come first, and then only the remaining non-virtual ones.