Skip to main content
GameDev.net gamedev.net
🔒 Locked

polymorph pointers

Started by pixienick Sep 14, 2004 at 10:42 AM 1 replies 850+ views
Original Post
pixienick
pixienick
Okay, i gotta a class, i gotta subclass, and somewhere else theres this function that returns a pointer to the superclass. But maybe sometimes the thing thats getting returned is the subclass. And maybe where its getting returned to could be either. And funnily enough it dosent work. class shape class square : public shape class bag square *thing; shape* getshape() { return thing; } } main() { bag one; square two; two = one.getshape(); } Should it work? can it work? Any suggestions would be much appreciated. Cheers
Agony
Agony
You can't assume that the pointer you're getting from getshape() is a square. All you know is that it is a shape, so you should throw the returned pointer into a shape pointer. From there, you can use RTTI (run-time type information) (C++'s, or your own if you wish) to determine if it is a square (or circle or polygon, etc.). You can then use a dynamic_cast<>() if I remember correctly, to get a pointer of the appropriate subclass type.

Otherwise, if you just assume it's a sqare, you're asking for trouble.
"We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas nly, and not for things themselves." - John Locke o
Miserable
Miserable
Quote:
Original post by Agony
You can't assume that the pointer you're getting from getshape() is a square. All you know is that it is a shape, so you should throw the returned pointer into a shape pointer. From there, you can use RTTI (run-time type information) (C++'s, or your own if you wish) to determine if it is a square (or circle or polygon, etc.). You can then use a dynamic_cast<>() if I remember correctly, to get a pointer of the appropriate subclass type.

Otherwise, if you just assume it's a sqare, you're asking for trouble.

Also note that while you can use, say, a dynamic_cast to safely cast it to a subclass (the cast will return a null pointer if it fails), you usually shouldn't. Polymorphic behaviour is intended exactly for situations where you don't need to know the exact type. Use the base class interface (where by 'base' I mean whatever type the pointer corresponds to, whether that is at the root of the inheritance hierarchy or somewhere in the middle).

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.