Search code examples
c++visual-c++inheritancediamond-problem

C++ Weird Diamond inheritance issue


I have this

    A
  /   \
 B     C
  \   /
    D

A has a pure virtual function, prototyped as:

virtual A* clone(void) const = 0;

B and C virtually inherit from A ( class B: public virtual A, class C: public virtual A)

B has the virtual function, prototyped as:

virtual B* clone(void) const {}; 

C has the virtual function, prototyped as:

virtual C* clone(void) const {};

D inherits from both B & C like that: class D: public B, public C D has the virtual function, prototyped as:

virtual D* clone(void) const {};

Now, when compiling I get the following 6 lines of errors:

error C2250: 'D' : ambiguous inheritance of 'B *A::clone(void) const'

No freaking idea how to solve this issue.

Thanks in advance.


Solution

  • avoid diamond inheritance? ;->

    anyway, here is sample (really sample - don't cast like that)

    // ConsoleCppTest.cpp : Defines the entry point for the console application. //

    #include "stdafx.h"
    #include "iostream"
    
    class A {
    public:
        virtual void* clone() = 0;
    };
    
    class B: public A {
    public:
        virtual void* clone() = 0;
    };
    
    class C: public A {
        public:
        virtual void* clone() = 0;
    };
    
    class D: public B, public C
    {
    public:
    
    
        virtual void* B::clone() 
        {
            std::cout << "B";
            return (void*)this;
        }
    
        virtual void* C::clone()
        {
            std::cout << "C";
            return (void*)this;
        }
    };
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    
        D* d = new D();
    
        void* b = ((B*)d)->clone();
    
        void* c = ((C*)d)->clone();
    
        return 0;
    }