Sign in to follow this  

polymorph pointers

This topic is 4839 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
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

This topic is 4839 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this