C++ primer 5th ed. Virtual inheritance and ctor-init

On C++ primer 5th Ed. Chapter 18. Multiple and virtual inheritance, I have this question:

Exercise 18.30: Define a default constructor, a copy constructor, and a constructor that has an int parameter in Base. Define the same three constructors in each derived class. Each constructor should use its argument to initialize its Base part.

I’ve tried to solve it this way so here is my inheritance hierarchy:

struct Class {
    Class(){cout << "Class()n";}
    ~Class(){cout << "~Class()n";}
};

struct Base : Class {
    Base(){cout << "Base()n";}
    Base(int){cout << "Base(int)n";}
    Base(Base const&){cout << "Base(Base const&)n";}

    ~Base(){cout << "~Base()n";}
};

struct D1 : virtual public Base {
    D1(){cout << "D1()n";}
    D1(int x) : Base(x){
        cout << "D1(int)n";
    }
    D1(D1 const& rhs) : Base(rhs){
        cout << "D1(D1 const&)n";
    }

    ~D1(){cout << "~D1()n";}
};

struct D2 : virtual public Base {
    D2(){cout << "D2()n";}
    D2(int x) : Base(x){
        cout << "D2(int)n";
    }
    D2(D2 const& rhs) : Base(rhs){
        cout << "D2(D2 const&)n";
    }
    ~D2(){cout << "~D2()n";}
};

struct MI : public D1, public D2 {
    MI(){cout << "MI()n";}
    MI(int x) : Base(x), D1(x), D2(x){
        cout << "MI(int)n";
    }
    MI(MI const& rhs) : Base(rhs), D1(rhs), D2(rhs){
        cout << "MI(MI const&)n";
    }

    ~MI(){cout << "~MI()n";}
};

struct Final : public MI, public Class {
    Final(){cout << "Final()n";}
    Final(int x) : MI(x){
        cout << "Final(int)n";
    }
    Final(Final const& rhs) : MI(rhs), Class(rhs){
        cout << "Final(Final const&)n";
    }

    ~Final(){cout << "~Final()n";}
};

Now if I compile the program I get the error:

 error: ‘Class’ is an ambiguous base of ‘Final’

So the problem is in the class Final‘s copy-constructor initialization-list so how could I initialize the subpart of Class in the Copy-constructor.

  • The Final(int) doesn’t complain because I’ve let the default ctor of Class() run:

      Final(int x) : MI(x) // Class default ctor is executed.
    

So help me to get around this problem. Thank you!

Source: Windows Questions C++

LEAVE A COMMENT