Consider the below code:
#include
using namespace std;
class A
{
public:
A() {cout << \"1\";}
A(const A &obj) {cout <<
First, lets change your inheritance as currently it is private:
class B : virtual protected A {...};
class C : virtual protected A {...};
Now, in your copy constructor, explicitly specify that the copy constructors of A and B and C should be called:
class D : protected B, protected C {
D(const D & obj) : A(obj), B(obj), C(obj) {cout << "8";}
};
And the output will be as desired (2468).
When we have virtual base classes, they must be initialized by the most derived class, otherwise there would be ambiguity concerning whether B or C for example is responsible for the construction of A.
§12.6.2, (13.1):
In a non-delegating constructor, initialization proceeds in the following order:
- First, and only for the constructor of the most derived class (1.8), virtual base classes are initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base classes in the derived class base-specifier-list.
In particular, if you define a copy constructor, and omit the list of copy constructors it should call, then the default constructors will be used.