Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

warning: base class ‘A’ should be explicitly initialized in the copy constructor

I've got the following class-structure:

class A{
   A(){}
   A(const A& src){}
};

class B : virtual A {
   B():A(){}
   B(const B& src):A(src){}
};

class C : virtual A {
   C():A(){}
   C(const C& src):A(src){}
};
class D : virtual B, virtual C {
   D():B(),C(){}
   D(const D& src):B(src),C(src){}
};

This gives me the warning:

In copy constructor ‘D’:

warning: base class ‘A’ should be explicitly initialized in the copy constructor

Which I dont unterstand. The Copy -Constructor of D calls the copy-ctor of B which calls the copy-ctor of A. Why does it want me to call the copy-ctor of A in D?

If I would do so, wouldnt the copy-ctor of A be called twice? Once called from B and once called from D.

Any input on this is much appreciated.

like image 472
veio Avatar asked Oct 24 '22 10:10

veio


2 Answers

Now I have confirmed that I was right, B used virtual inheritence to derive from A.

When that happens, the most derived class is responsible for constructing the base class. This allows the multiple inheritence diamond.

======== A ============
   ^            ^
   B            C
    \           /
     \         /
      \       /
       \     /
          D

D derives from B and C and both derive from A so D would inherit 2 copies of A, one from B and one from C.

If B1 and B2 both use virtual inheritence to derive from A, then the final class must initialize the base class, i.e. A, thus ensuring just once instance.

This is why you got the error message.

like image 178
CashCow Avatar answered Nov 15 '22 06:11

CashCow


The Copy -Constructor of D calls the copy-ctor of B which calls the copy-ctor of A.

No, it doesn't. A virtual base class is always initialized by the most derived class being constructed. Initializations in member initializer lists for classes in the inheritance hierarchy that are not the most derived class for the object under construction are ignored. A virtual base class can only be initialized once and the rule is that the most derived class will do this either explicitly, or implicitly if the base class does not appear in the member initializer list of the most derived class constructor being used.

As the warning hints, for a copy constructor you almost certainly want to explicitly initialize the virtual base class from the object being copied.

like image 44
CB Bailey Avatar answered Nov 15 '22 06:11

CB Bailey