2

Having an exam in OOP. They absolutely love to ask about the initialize order of constructors in C++. For example, they ask what would be the output of the given program:

struct A {
   int x;
   A() : x(1) { cout << "A" << endl; }
   A(int i) : x(2) { cout << "A int " << i << endl; }
};
struct B : virtual public A {
   int x; B() : A(), x(3) { cout << "B" << endl; }
   B(int i) : A(), x(4) { cout << "B int " << i << endl; }
};
struct C1 : public B {
   int x;
   C1(int i) : B(i), x(5) { cout << "C1 " << endl; }
   virtual void foo() { cout << "foo " << x << endl; }
};
struct C2 : virtual public B {
   int x; C2() : B(), x(6) { cout << "C2" << endl; }
   virtual void bar() { cout << "bar " << x << endl; }
};
struct D : public C1, public C2 {
   int x;
   D(): C1(7), C2(), x(8) { cout << "D" << endl; }
};

D* d = new D();
C1* c1 = d;
A* a = d;

The output should be:

A
B
B int 7
C1
C2
D

I'm having a really bad time of trying to understand why the output is like this. I'm looking for an algorithm I could follow so I can answer those types of questions on the exam.

vesii
  • 2,760
  • 4
  • 25
  • 71
  • You could have a look at cppquiz.org they have a lot of questions like this together with a good explanation. Maybe a good resource for practicing – choosyg Sep 16 '19 at 11:27

0 Answers0