How to call copy constructor of all base classes for copying most derived class object in diamond inheritance in C++?

前端 未结 4 1742
囚心锁ツ
囚心锁ツ 2021-02-15 23:31

Consider the below code:

#include
using namespace std;
class A
{
public:
     A() {cout << \"1\";}
     A(const A &obj) {cout <<          


        
4条回答
  •  南旧
    南旧 (楼主)
    2021-02-16 00:07

    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).

    Why?

    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.

提交回复
热议问题