Right, I am fairly new to c++ so I am still learning here. If I am going about this in the wrong way then tell me, but try to point me in the right direction if possible (perhpaps with a link to a tutorial).
I have being playing around with std::map and have used it to store an object (item). This works fine. The problem is trying to store derived items within the map. I have got it working but it seems to be slicing up the derived object.
So say item has the attributes a,b and c. and food is derived from item with the extra attributes d and e. I cannot access d and e when it is stored in a map of items. The compiler says:
“error: ‘class item’ has no member named ‘d’”
Is it possible to use std::map polymorphicaly or do I need to use another library like boost? Boost seems rather complex and I was hoping that there was a way to do it with map while I am still learning. Here is some of the code that I am playing with to make it clearer what I mean.
Map of items is declared as so:
typedef std::map <int, tItem*> itemMap;
Things are added to it like this:
Item * item = new Item (a, b, c);
itemmap [vnum] = item;
DerivedItem * deriveditem = new DerivedItem (a, b, c, d, e);
itemmap [vnum] = deriveditem;
This works, but I cannot access d and e of the derived item.
Thanks for the help guys
You can use
dynamic_castto cast back to the derived class, if you knwo what class it is.http://en.wikipedia.org/wiki/Dynamic_cast
If you want this to be done automatically, you can derive a new template class from std::map, where the
[]operator has a template argument. But in this case you have to pass the type when you get the item: