#include <iostream>
using namespace std;
struct A{
A() {cout << "A" << endl;}
A(int a) {cout << "A+" << endl;}
};
struct B : virtual A{
B() : A(1) {cout << "B" << endl;}
};
struct C : virtual A{
C() : A(1) {cout << "C" << endl;}
};
struct D : virtual A{
D() : A() {cout << "D" << endl;}
};
struct E : B, virtual C, D{
E(){cout << "E" << endl;}
};
struct F : D, virtual C{
F(){cout << "F" << endl;}
};
struct G : E, F{
G() {cout << "G" << endl;}
};
int main(){
G g;
return 0;
}
Program prints:
A
C
B
D
E
D
F
G
I would like to know what rules should I use to determine in what order constructors get called. Thanks.
Virtual base subobjects are constructed first, by the most-derived class, before any other bases. This is the only way that makes sense, since the relation of the virtual bases to tbe most-derived object is not known until object construction, at runtime (hence "virtual"). All intermediate initializers for virtual bases are ignored.
So, what are your virtual bases?
G
derives fromE
andF
.E
derives virtually fromC
, which in turn derives virtually fromA
, soA
,C
are first. Next,F
doesn't add any further virtual bases. Next,E
has non-virtual basesB
andD
, in that order, which are constructed next, and thenE
is complete. Then comesF
's non-virtual baseD
, andF
is complete. Finally,G
is complete.All in all, it's virtual bases
A
,C
, then non-virtual basesB
,D
,E
andD
,F
, and thenG
itself.You can investigate the order of constructor calls from this quote of the C++ Standard and try to trap it yourself
You should follow the rules given in the C++ standard: