struct BaseObject
{};
struct HardMonster : BaseObject
{
int Berserk(int);
private:
std::list<BaseObject> MonsterList;
};
I have all the monsters defined as a BaseObject, so it's easier to make a list of them. But when I need to convert the BaseObject into a HardMonster so I can use to the Berserk function. I know, I could do it the easy and just make a temp Hardmonster to calculate the damage from Berserk. But I want to do it the right way.
If you use:
you will be storing only
BaseObject
s. If you add any object of derived type to the list, you will lose the derived type part in the stored object.Further reading: What is object slicing?
What you need to store is pointers, preferably smart pointers, to
BaseObject
s.From a
std::shared_ptr<BaseObject>
, you can get astd::shared_ptr<HardMonster>
by usingdynamic_pointer_cast
.