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

南楼画角 提交于 2019-12-05 13:22:04

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.

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.

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

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