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

Domanda

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?

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top