How do you downcast from a base object to a child one

83 views Asked by At
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.

1

There are 1 answers

0
R Sahu On

If you use:

list<BaseObject> MonsterList; //This is where the Object list is defined.

you will be storing only BaseObjects. 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 BaseObjects.

std::list<std::shared_ptr<BaseObject>> MonsterList;

From a std::shared_ptr<BaseObject>, you can get a std::shared_ptr<HardMonster> by using dynamic_pointer_cast.

std::shared_ptr<BaseObject> baseObject;
std::shared_ptr<HardMonster> monster = std::dynamic_pointer_cast<HardMonster>(baseObject);
if ( monster )
{
    // The cast is successful...
    // Use monster
}