user1079425
user1079425

Reputation:

virtual derivation & conversion ambiguous

I'm learning now the different situations of ambiguity in the virtual derivation on C++. But I have an error of Ambiguity in my code and I don't understand it's reason...

Here's my Code :

class V {
    public:
        int v ;
};

class A {
    public:
        int a ;
};

class B : public A, public virtual V {

};

class C : public A, public virtual V {

};

class D : public B, public C {
    public:
        void f() ;
};

void g() {
    D d ;
    B* pb = &d ;  // No Problem
    A* pa = &d ;  // Error: 'A' is ambiguous base of 'D'
    V* pv = &d ;  // No Problem
}

I don't understand why do I have this error however I don't have errors for the other affectations.

Thank you :-)

Upvotes: 1

Views: 2275

Answers (1)

Alain
Alain

Reputation: 27220

This is completely expected in cases of multiple inheritance. What we have here is a case of Diamond inheritance. D now has two copies of A, one inherited from B, and one inherited from C. You need to specify which of B or C the members of A exposed to D come from.

See: Using C++, how do I correctly inherit from the same base class twice?

You might consider:

  • Using virtual inheritance:

    class B : public virtual A, public virtual V {...};

    class C : public virtual A, public virtual V {...};

  • Using composition as a way out of multiple inheritance.

I suggest reading Solving the Diamond Problem with Virtual Inheritance

Upvotes: 2

Related Questions