Search code examples
c++multiple-inheritancediamond-problem

C++ Resolving the diamond problem


Couldn't the diamond problem be resolved just by using the first inherited declaration found? I mean,

public class A {
    public virtual int getInt();
};

public class B : public A {
    public int getInt() {return 6;}
};

public class C : public A {
    public int getInt() {return 7;}
};

public class D: public B, public C {};

for class D, since B is listed first, couldn't we just by default (when it's ambiguous) use B::getInt() if D::getInt() is called? Kind of how the PATH environment variable works in UNIX and other OS's; if two things exist with the same name in different locations in the PATH variable, then the first location shall be used by default (unless otherwise qualified).

Edit: by 'first' inherited declaration found I mean according to simple left-to-right depth-first order

Edit#2: Just updated the above implementation to be more diamond-like.


Solution

  • It's a very buggy solution. Think what will happen in the following case:

    public class A {
        public int getInt() {return 5;}
        public float getFloat() {return 5.0;}
    };
    
    public class B {
        public int getInt() {return 6;}
        public float getFloat() {return 6.0;}
    };
    
    public class C {
        public int getInt() {return 7;}
        public float getFloat() {return 7.0;}
    };
    
    public class D: public A, public B, public C {}
    

    Suppose that one will want D::getInt to return 5 while another developer wants D::getFloat to return 7.0 (thus, different functions resolved to different ancestors). The second developer will change the order of inheritance and a bug will creep in all code paths depending on getInt.