0

I have these simple classes:

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

class Player : public Entity {
private:
    std::string name_;
public:
    Player(const std::string& name): name_(name) {}

    std::string getName() {
        return name_;
    }
};

When I run this code:

void print(const std::string& msg) {
    std::cout << msg << std::endl;
}

int main () {
    Player player("hello");
    print(player.getName());


    Entity e = player;
    print(e.getName());
}

I expect "hello" to be printed twice, but I get the following output, despite getName() being marked virtual in the superclass:

hello
Entity

However, if I run the code like this:

int main () {
    Player* player = new Player("hello");
    std::cout << player->getName() << std::endl;


    Entity* e = player;
    std::cout << e->getName() << std::endl;
    return 0;
}

I get the following output as expected:

hello
hello

Why would the behavior be different when these are pointers instead of stack-allocated variables? Am I doing something wrong when declaring them on the stack? Thanks!

0 Answers0