Anthony
Anthony

Reputation: 301

Calling a derived virtual function

I'm still fairly new to C++ and inheritance has gotten me in a pickle. I know this works in C# since I'm always using Base.();

I'm hoping to be able to call a vector array of PlayerCharacter, derived from Entity. Currently when I call it, it only calls Entity's update method.

int main()
{
vector<Entity*> list;
list.push_back(&PlayerCharacter());

   for(int i = 0; i < list.size(); i++)
   {
   list[0]->Update();
   }
}

class Entity
{
public:
    Entity(void);
   ~Entity(void);
    int hitpoints;
    virtual void Update(void);
};
void Entity::Update(void)
{
    int a = 0;
    a++;
}
class PlayerCharacter : public Entity
{
public:
    PlayerCharacter(void);
    ~PlayerCharacter(void);
    bool Move();
    void Update() override;
};
void PlayerCharacter::Update(void)
{
    int a = 0;
    a--;
}

Upvotes: 3

Views: 114

Answers (2)

Biraj Borah
Biraj Borah

Reputation: 101

This Works : Few changes though : 1) You dont need to put Override 2) Definition of Constructor and destructor once declared 3) Created object of derived class and passed it to the list.

Output is : Inside PlayerCharacter

If you want to call base class update method method remove the volatile keyword. Or use base class pointer pointing to base class object.

class Entity
{
public:
    Entity();
    ~Entity();
    int hitpoints;
    virtual void Update(void);
};

Entity::Entity()
{
}
Entity::~Entity()
{
}
void Entity::Update(void)
{
    std::cout << " Inside Entity" <<std::endl;
    int a = 0;
    a++;
}
class PlayerCharacter : public Entity
{
public:
    PlayerCharacter();
    ~PlayerCharacter();
    bool Move();
    void Update();
};
void PlayerCharacter::Update(void)
{
    std::cout << " Inside PlayerCharacter" <<std::endl;
    int a = 0;
    a--;
}

PlayerCharacter::PlayerCharacter()
{

}

PlayerCharacter::~PlayerCharacter()
{    

}
int main()
{
    vector<Entity*> list;
    PlayerCharacter ObjPlayerCharacter;
    list.push_back(&ObjPlayerCharacter );

    for(unsigned int i = 0; i < list.size(); i++)
    {
        list[0]->Update();
    }
}

Upvotes: -1

Raxvan
Raxvan

Reputation: 6505

list.push_back(&PlayerCharacter()); i think this is undefined behavior in your code.

In your case you should allocate the data on the heap like this: list.push_back( new PlayerCharacter() ); otherwise if you do this &PlayerCharacter() then the PlayerCharacter variable will be destroyed immediately and the pointer inside the list will point to garbage bytes.

Also to track which function is called you can use the debugger or print something in the console from each Update function.

Upvotes: 4

Related Questions