The procedure for creating virtual base classes

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 will be as follows:

A1 A2 A1 AA2 A2 AA1 B

I want to understand where the first one is created A1.

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

+4
source share
2 answers

The first A1is the result of the initialization of the (virtual) base (not virtual) AA1of B.

B , A1, A2 AA2. ( AA2 A1 AA2.) , , AA1 ( A2 AA1), , , , B. , .

+2

B : A1, A2 AA2, .

A1 A2, , A1 A2, AA2 A1, AA2, A1, A1 AA2.

, :

#include <iostream>

struct A1 {
    A1(const char *s) { std::cout << "A1(" << s << ")\n"; }
};

struct A2 {
    A2(const char *s) { std::cout << "A2(" << s << ")\n"; }
};

struct AA1 : virtual A1,  A2 {
    AA1(const char *s) : A1("AA1"), A2("AA1") { std::cout << "AA1(" << s << ")\n"; }
};

struct AA2 : A1, virtual A2 {
    AA2(const char *s) : A1("AA2"), A2("AA2") { std::cout << "AA2(" << s << ")\n"; }
};

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

int main() {
    B b;
}

:

A1(B)
A2(B)
A1(AA2)
AA2(B)
A2(AA1)
AA1(B)
B()

, , :

  • A1 A2 AA2, A2 A1 ( , A1 - ).
  • AA1 AA2 B, AA2 ( ).
+2

Source: https://habr.com/ru/post/1670190/


All Articles