3

I can't seem to get multilevel inheritance function calls working properly. For my structure I have a "Entity" as the main super class then

Entity -> Bullet, Agent

Agent -> Player, Enemy

Enemy -> BasicEnemy

In each of these I have an "update" function

class Entity
{
public:
    Entity();
    virtual ~Entity();
    //stuff
    virtual Bullet update(float deltaTime);
 }


class Agent : public Entity
{
public:
    Agent();
    virtual ~Agent();

    virtual Bullet update(float deltaTime);

class Player : public Agent
{
public:
    Player();
    ~Player();

    Bullet update(float deltaTime) override;

class Enemy : public Agent
{
public:
    Enemy();
    virtual ~Enemy();

    virtual Bullet update(float deltaTime);

class BasicEnemy : public Enemy
{
public:
    BasicEnemy();
    ~BasicEnemy();

    Bullet update(float deltaTime) override;

I create player, enemy, and bullet objects then pass them into a vector of entities however whenever I call

Entity entity = entities[i];
entity.update(deltaTime);

It only every goes into the "Agent" update function and if i make the Agent update function pure virtual it just goes to the Entity update function, why don't the player and enemy update functions overwrite the base functions?

MolerC
  • 67
  • 8

1 Answers1

5

This is because you store objects in the vector. You should store object's pointers.

Details: In C++ if you cast an Agent object to an Entity object you loose all the information about the Agent and the new object will be a real Entity. I.e. you loose the polymorphic behavior.

This happened when you created a vector with Entity object and pushed and Agent object in it because the stored objects will be pure Entity objects.

In C++ the references and the pointers keep the polymorphism. Therefore to solve the issue you should create a vector of pointers:

std::vector< Entity* > entities;
entities.push_back( new Agent( ) );
entities[ 0 ]->update( 5); // Agent::update will be called
Tibor Takács
  • 3,535
  • 1
  • 20
  • 23