Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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--;
}
like image 377
Anthony Avatar asked Feb 02 '26 18:02

Anthony


1 Answers

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.

like image 140
Raxvan Avatar answered Feb 05 '26 06:02

Raxvan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!