C++ Resolving the diamond problem

后端 未结 2 1105
面向向阳花
面向向阳花 2021-01-22 13:01

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 cl         


        
相关标签:
2条回答
  • 2021-01-22 13:15

    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.

    0 讨论(0)
  • 2021-01-22 13:21

    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.

    0 讨论(0)
提交回复
热议问题