I am having several problems trying to downcast a class into another one to access an specific method of that class. This is my current scheme of classes:
GameObject class:
class GameObject
{
...
}
Enemy class:
#include "../GameObject.h"
class Enemy : public GameObject
{
Enemy(Type type);
virtual ~Enemy();
virtual int receiveDamage(int attack_points);
virtual void levelUp() = 0;
...
protected:
char *name_;
int level_;
int health_;
int max_health_;
int attack_;
int armor_;
}
SmallGoblin class:
#include "../Enemy.h"
class SmallGoblin : public Enemy
{
public:
SmallGoblin();
~SmallGoblin();
void levelUp();
}
In my code, I try to do this and a std::bad_cast exception is thrown every time.
class Player : GameObject
{
...
virtual void attack(GameObject &enemy)
{
try
{
Enemy &e = dynamic_cast<Enemy&>(enemy);
e.receiveDamage(attack_points_);
}
catch(const std::bad_cast& e)
{
std::cerr << e.what() << '\n';
std::cerr << "This object is not of type Enemy\n";
}
}
...
}
(enemy is a reference to a GameObject object, however I know it's actually a SmallGoblin object).
In other part my code I have anoother class (Door) which extends the GameObject class and the downcasting works (however, I have to use static_cast instead dynamic_cast I don't know why).