Jump to content
  • Advertisement
Sign in to follow this  
ozenc

inheritance-type casting problem

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

Hi, I have a base class named BasePrimitive and two other classes named Rectangle & Circle which are derived from BasePrimitive class. Basically what I am trying to do is to store Circle and Rectangle objects in a common container. (std::vector<BasePrimitive> shapeList). There is no problem when using push_back to store these objects. However I cannot retrieve these objects back because I cannot type cast them. (BasePrimitive class has a type enumeration and I am trying to type cast wrt to its value) I have tried all type casting methods I know including, dynamic_cast & reinterpret_cast, but it didnt help. Is there a way to type cast or is there a way around this problem in C++. (I know I can use union but, I'd rather prefer a neater C++ way of solution since inheritance is involved ;) ) Thanks for your help..

Share this post


Link to post
Share on other sites
Advertisement
Storing polymorphic types in a vector by value is a no-no. Instead consider using a vector of (smart) pointers to the base class. The problem you have now is called slicing, where you copy a derived class to a base class and the derived class' information is lost.

Share this post


Link to post
Share on other sites
Quote:
Original post by SiCrane
Storing polymorphic types in a vector by value is a no-no. Instead consider using a vector of (smart) pointers to the base class. The problem you have now is called slicing, where you copy a derived class to a base class and the derived class' information is lost.


Just to add to that, it can also be the case with C-style dynamic arrays i.e. base_type* foo = new base_type[N]; .... foo = some_derived_instance; can also cause slicing.

Share this post


Link to post
Share on other sites
Quote:
Original post by SiCrane
Storing polymorphic types in a vector by value is a no-no. Instead consider using a vector of (smart) pointers to the base class.


Or in lieu of directly using a (smart) pointer, a pointer based container - e.g. boost::ptr_vector [link].

Share this post


Link to post
Share on other sites
Thanks for the quick replies. A couple of changes and it works now. By the way, thanks for the link, I am checking it out now :)

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!