Skip to main content
gamedev.net
🔒 Locked

inheritance-type casting problem

Started by ozenc Sep 13, 2005 at 7:22 AM 3 replies 700+ views
Original Post
ozenc
ozenc
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 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..
SiCrane
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.
snk_kid
snk_kid
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.
MaulingMonkey
MaulingMonkey
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].
ozenc
ozenc
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 :)

Topic Locked

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

Sign in to reply to this topic.