C++: Redefine one or the other operation in the child class
In the following code:
class GraphicalCardDeck : public CardDeck, public GraphicalObject {
public:
virtual void draw () {
return CardDeck::draw();
}
virtual void paint () {
开发者_如何学Go GraphicalObject::draw();
}
}
GraphicalCardDeck gcd;
gcd->draw(); // selects CardDeck draw
gcd->paint(); // selects GraphicalObject draw
When in the class CardDeck
there is a function named draw
, and in the class GraphicalObject
there is a function named draw
.
The book mentions a problem when we do:
GraphicalObject* g = new GraphicalCardDeck();
g->draw(); // opps, doing wrong method!
Why will it call the wrong method? It will not call the function draw
in the class CardDeck
as we define?
Thank you.
Yes, it will call the function draw
in the CardDeck
as we defined. But that might be surprising to someone not familiar with the internals of our class:
GraphicalObject* g = new GraphicalCardDeck();
g->draw(); // opps, doing wrong method!
Someone that wrote this might expect that GraphicalObject::draw()
is called (or at least an overwritten version of that function that provides the same functionality). Since our overwritten function provides completely different functionality (that required by CardDeck
), from the perspective of the one writing the above code the "wrong" function is called (aka. not the one he intended to call).
So it works like you expected, but when just looking at the interface and without knowledge of the internal implementation one might expect different behavior.
精彩评论