Why can't I cast super class reference to a subclass that is extending another super class as well?

StackOverflow https://stackoverflow.com/questions/22649077

I'm trying to understand the diamond problem in inheritance and I was simulating it. This is what I have:

using namespace std;

class top {
    int a;
};

class left : public top {
    int b;
};

class right : public top {
    int c;
};

class bottom : public left, public right {
    int d;
};

int main() {

    bottom* b = new bottom ();

    left* l = (left*) b;
    right* r = (right*) b;

    cout << l << " " << r << endl;
    return 0;
}

Shouldn't I be able to achieve this ? Most of the tutorials say this is possible. However I'm getting compiler error saying it is ambiguous. Can someone give an explanation and some context here?

有帮助吗?

解决方案

You should avoid using namespace std as std::left and std::right clash with your own definitions.

See http://ideone.com/tMa28j for a working version.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top