Question

All objects in my program inherit from a Container class. The Container class has a virtual BaseNode* getParent() const; method and a virtual void setParent(BaseNode *p); method.

I have a Set class (Set in a tennis match, not a data structure) which has the Match class as it's parent (via setParent()) but since Set inherits from Container, The program creates a tree structure from the top down and the Set class is a child, it doesn't need to have methods to track and maintain information about it's parent beyond what Container provides.

The error C++: invalid conversion from ‘BaseNode*’ to ‘Match*’ shows up in the method below when I try to compile my program. (Player* getPlayer1() const; only exists in the Match class)

Player* Set::getPlayer1() const{
    return getParent()->getPlayer1();
}

This is my inheritance structure for Match. (Note that TreeNode is a template)

Match -> TreeNode<Set> -> BaseNode -> Container

I don't understand why I'm getting a conversation error. I have tried reading my textbook but it's a rather poor reference. Google just provided too much irrelevant information.

Edit

Player* Set::getPlayer1() const{
    return dynamic_cast<Match>(getParent())->getPlayer1();
}

causes

error: cannot dynamic_cast ‘#‘obj_type_ref’ not supported by dump_expr#<expression error>((&((const Set*)this)->Set::<anonymous>))’ (of type ‘class BaseNode*’) to type ‘class Match’ (target is not pointer or reference)

Edit 2

I just realized I need dynamic_cast<Match*> which works.

Was it helpful?

Solution

The problem is that getParent() returns a BaseNode*, which could be a pointer to any type of BaseNode - it might point to an unrelated class that also derives from BaseNode. If you're 100% sure that the parent must be of type Match, you should cast the parent to a Match* first, and then you can call getPlayer() on that:

Player* Set::getPlayer1() const{
    return dynamic_cast<Match*>(getParent())->getPlayer1();
}

If the parent isn't necessary a Match, then dynamic_cast might return NULL, so be sure to check for that.

OTHER TIPS

I think you really need to re-organize your hierarchy and method names... This has nothing to do with your question, but in general it seems hard to fathom why Set inherits from Match. (doesn't a match have sets?)

games are composed of points, sets are composed of games and a match is composed of sets... a point is won by a player.

you should probably structure it more closely to the real world.

just my $.02

EDIT

I'd probably have a Match object that contains a map of sets (map i.e. set one, two three, etc) and the Method Player(int) rather than Player1() and player2(). Also it does not seem necessary to have a method for player in the Set class. A Set would point to a match in which it is being played.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top