0
#include<iostream>

class Entity {
public:

    virtual int get_name() { return 1; }
};

class Player : public Entity {
public:
    int m_Name;

    Player(const int name) {
        m_Name = name;
    }

    int get_name() override { return m_Name; }
};

void print(Entity entity) {
    std::cout << entity.get_name() << std::endl;
}

int main() {

    Entity e;
    Player p(2);

    print(e);
    print(p);
    std::cin.get();
}

Why does print(e) and print(p) both return 1? p.m_Name is 2 in the debugger and if I change print to take a Player, it prints 2.

Simon
  • 1
  • 1
    The print function slices anything you pass it down to an Entity because the parameter is passed by value. Use a reference instead. – Retired Ninja Sep 26 '21 at 22:25
  • 1
    In C++, using polymorphism requires passing arguments to a function's parameters that are references (or pointers, but sticking with references is my recommendation). – Eljay Sep 26 '21 at 22:47
  • Even before getting into polymorphism you want `void print(Entity& entity)` (or better `void print(Entity const& entity)`). That will make the polymorphism work. – alfC Sep 26 '21 at 22:51

0 Answers0