dimanche 12 janvier 2020

Stack allocation of virtual function leads to unexpeted behavior (calls base class method instead of child class)

I have a basic class which is getting inherited by inherited class player.

class Entity{
   public:
    virtual std::string getName(){ return "Hello World";}
 };

In my extended class I am just trying to override getName method like following snippet:

  class Player : public Entity{
    public:
    std::string getName() override { return "Hello from Player"; }
  };

When I allocate the object on heap it calls the right extended class method, I get output "Hello from Player" allocation object on heap is done like:

Entity* e= new Entity;
  Player* p = new Player;
  Entity* entity = p;
  std::cout << entity->getName() <<std::endl;

But when I allocate the same object on stack, it calls the base method instead of overridden method, I have done stack allocation as:

Entity e1;
  Player p1;
  Entity entity1 = p1;
  std::cout << entity1.getName() <<std::endl;

The combined output of the whole code looks like:

Hello from Player -------------- Hello World

I am using clang version 7.0.0-3~ubuntu0.18.04.1 with c++11 flag, was hoping if can any one explain to me this behavior. Isn't stack or heap allocation suppose to have no effect on how object behaves? or am I missing something? I have tried to google the topic without getting any accurate relevant answers. Here is a repl.it link: https://repl.it/repls/GleefulDroopyRay

Aucun commentaire:

Enregistrer un commentaire