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

微笑、不失礼 提交于 2019-12-07 09:49:06

问题


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.


回答1:


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.




回答2:


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.




回答3:


The reason is the virtual inheritance. Because of that A should be initialized explicitly.



来源:https://stackoverflow.com/questions/9098979/warning-base-class-a-should-be-explicitly-initialized-in-the-copy-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!