Given the following code in C++:

struct A {
    A() { f(0); }
    A(int i) { f(i); }
    virtual void f(int i) { cout << i; }
};
struct B1 : virtual A {
    B1(int i) : A(i) { f(i); }
    virtual void f(int i) { cout << i+10; }
};
struct B2 : virtual A {
    B2(int i) : A(i) { f(i); }
    virtual void f(int i) { cout << i+20; }
};
struct C : B1, virtual B2 {
    int i;
    C() : B1(6),B2(3),A(1){}
    virtual void f(int i) { cout << i+30; }
};

Can someone explain why C* c = new C(); will print 1 23 and then 16 in that order? How does it decide which order to print in? I know that the nonvirtual B1 will be called last but why is A() called first? Thanks for the help and explanation ahead of time.

有帮助吗?

解决方案

Because your are virtually inheriting B2, the compiler will construct it first as to identify which variables are virtually inherited in C before it constructs any non-virtual inheritance (B1). Of course, A gets constructed first because B2 needs it before it can be constructed.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top