0

I'm working on a game for an assignment and I've ran into an issue with function overriding in C++.

I have the following structure:

class GameEntity
{
public:
    bool GameEntity::TakeHit(int dmg);
};

class Enemy : public GameEntity
{
    bool Enemy::TakeHit(int dmg);

};

When from another class I create an instance of an Enemy, store it in a GameEntity vector, then call TakeHit() on it, it's calling the GameEntity version of it. I'm used to Java where this would call the other version, am I doing something obviously wrong here?

Other questions don't really cover this so I've created my own.

It's probably something pretty simple I'm guessing, so apologies for the trouble.

Vũ Tài
  • 1
  • 1

2 Answers2

2
  1. Make TakeHit a virtual member function.

    // You don't need the scope specifier GameEntity::
    // Make it pure virtual to force sub-classes to implement them.
    virtual bool TakeHit(int dmg) = 0;
    
  2. Store pointers to objects, preferably smart pointers, instead of objects. If you store just objects, you suffer from object slicing problem.

Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

The function from GameEntity needs the virtual keyword.

NaCl
  • 2,683
  • 2
  • 23
  • 37