0

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.

Mgetz
  • 5,108
  • 2
  • 33
  • 51
Wes Field
  • 3,291
  • 6
  • 23
  • 26
  • 3
    `A` is a base of `B2`, so it has to be constructed before `B2`. – Kerrek SB Jul 31 '13 at 21:16
  • Duplicates of: http://stackoverflow.com/questions/6247595/order-of-calling-base-class-constructor-from-derived-class-initialization-list and http://stackoverflow.com/questions/2669888/c-initialization-order-for-member-classes ? If you look up initialization order of base classes, you'll find plenty of reading material :) – Jens Jul 31 '13 at 21:35

1 Answers1

1

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.

Lochemage
  • 3,974
  • 11
  • 11