C++ Resolving the diamond problem

雨燕双飞 提交于 2019-12-02 02:41:18

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.

This is not a diamond problem. C++ compiler is specific about all its syntax, if there is any ambiguity it will always throw error.

Here your A::getInt(), B::getInt() and C::getInt() are ambiguous when you call simply d.getInt().

Edit:

In your edited question, still compiler doesn't evaluate from the inheritance, because some programmers may really need to have different copies of A==> 1st via class B and 2nd via class C. Note that so called diamond problem is a problem characterized by humans. For C++ compiler, it's just one more pattern.

In C++ philosophy, you are not restricted to only one paradigm or pattern. You can choose to have multiple inheritance of your choice.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!