Jump to content
  • Advertisement
Sign in to follow this  
pixienick

polymorph pointers

This topic is 5152 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
Advertisement
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.

Share this post


Link to post
Share on other sites
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).

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!