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

前端 未结 4 1723
囚心锁ツ
囚心锁ツ 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:13

    Alternative solution which doesn't require changing the inheritance modifiers of class B or C:

    class A
    {
    public:
         A() {cout << "1";}
         A(const A &obj) {cout << "2";}
    };
    
    class B: virtual A
    {
    public:
        B() {cout << "3";}
        B(const B & obj) {cout<< "4";}
    };
    
    class C: virtual A
    {
    public:
       C() {cout << "5";}
       C(const C & obj) {cout << "6";}
    };
    
    class D:B,C,virtual A
    {
    public:
        D() {cout << "7";}
        D(const D & obj) : A(obj), B(obj), C(obj) {cout << "8";}
    };
    

提交回复
热议问题