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

前端 未结 4 1716
囚心锁ツ
囚心锁ツ 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-15 23:55

    The way you have inherited your classes, all of them use private inheritance.

    By changing the inheritance of B from A and C from A to be protected or public, you can resolve the problem.

    class B : protected virtual A
    {
       ...
    }
    
    class C : protected virtual A
    {
       ...
    }
    

    or

    class B : public virtual A
    {
       ...
    }
    
    class C : public virtual A
    {
       ...
    }
    

    and then update D's copy constructor to:

    D(const D & obj) : A(obj), B(obj), C(obj) {cout <<"8";}
    

    PS It's baffling to me that the default constructor works even with private inheritance.

提交回复
热议问题