Derived virtual class, returning object

Hi guys,

I am having an issue I need some help with.

If I have a virtual base class such as...

1
2
3
4
5
6
7
8
class BaseItem{
public:
  virtual ~BaseItem(){}
  virtual int getValue()=0;
//more virtual funcitons

};


and a number of classes derived from the above pure virtual class such as...

1
2
3
4
5
6
7
class HealingPotion:public BaseItem{};

class ManaPotion:public BaseItem{};

class Weapon:public BaseItem{};




And I load up a vector thusly...

1
2
3
4
5
6
std::vector<BaseItem*> items;

items.push_back(new Weapon());
items.push_back(new ManaPotion());
items.push_back(new HealingPotion());


I need the ability to retrieve the derived item in this manner


TypeName type=items[current_value];

So, for example, if I have a Weapon at items[12], then I need the ability to access the sword type, and not the underlaying BaseItem type.

Any help would be greatly appreciated.

Thanks,

Mike



You need dynamic_cast. For example:
1
2
3
4
if (Weapon* weapon = dynamic_cast<Weapon*>(items[12]))
{
    // do weapon stuff
}
Thank kbw, works like a charm!

Topic archived. No new replies allowed.