开发者

C++ Resolving the diamond problem

开发者 https://www.devze.com 2023-03-20 17:28 出处:网络
Couldn\'t the diamond problem be resolv开发者_开发技巧ed just by using the first inherited declaration found? I mean,

Couldn't the diamond problem be resolv开发者_开发技巧ed 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号