1

Consider given code:

class A {
public:
    A(int x) {}
};

class B : public virtual A {
public:
    B(int x) : A(1) {}
};

class C : public virtual A {
public:
    C(int x) : A(2) {}
};

class D : public B, public C {
public:
    D(int x) : A(3), B(1), C(1) {}
};

class E : public D {
public:
    E(int x) : A(4), D(1) {}
};

My first question is why do we need to call constructor of A in initializtion list of E and D, as it is already specified in B and C? In other words why the following doesn't work?

class A {
public:
    A(int x) {}
};

class B : public virtual A {
public:
    B(int x) : A(1) {}
};

class C : public virtual A {
public:
    C(int x) : A(2) {}
};

class D : public B, public C {
public:
    D(int x) : B(1), C(1) {}
};

class E : public D {
public:
    E(int x) : D(1) {}
};

This way below code would call A(1), B(1), C(1), D(1), E(1). While the correct former version calls A(4), B(1), C(1), D(1), E(1)

E test(1); 

My other question is why we don't need to add constructors of B and C to initializtion list of E and do for D.

mikol
  • 185
  • 1
  • 10
  • Which constructor call of `A` choose ? you arbitrary use the one from B for E in your example... – Jarod42 Dec 27 '18 at 23:45

0 Answers0