0

I am making a game, in the game a have a list that holds the player, this list deals with the class Player. I also have a class the is a child of Player called HumanPlayer. I have added a a human player to the player list. but when I run a render function it doesn't render from humanplayer it renders from player. The render function is a virtual function, that should be overwritten but it not.

Here is where I define the list:

std::list<Player> playerList;

here is where I add a humanplayer to the list:

playerList.push_front(HumanPlayer(512,512,&entityList));

Here is where the render function calls the render:

if(!playerList.empty()){
    std::list<Player>::iterator iter;
    for (iter = playerList.begin(); iter != playerList.end(); iter++){
       iter -> render(canvas);
    }
 }
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • 4
    You are `slicing` http://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c, polymorphism requires `pointers`. – Shafik Yaghmour Apr 30 '13 at 17:22

3 Answers3

4

You are doing what it called Slicing. In order for polymorphism to work you need to use pointers or references. The most basic solution would be to use a pointer instead:

std::list<Player*> playerList;

but now you need to manage the memory and remember to delete all the instances you create. So as Collin suggested you could use some sort of smart pointer like std::shared_ptr. But ultimately you need to decided which makes more sense for your problem.

Community
  • 1
  • 1
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
  • Using pointers changes a number of things in his code; in particular, there will be just one instance of each player, not many. It's highly unlikely that `std::unique_ptr` would be appropriate here; `std::shared_ptr` _might_ be, but there's a good chance that the most appropriate pointer is a raw pointer. – James Kanze Apr 30 '13 at 17:30
  • @JamesKanze Thank you, amended answer – Shafik Yaghmour Apr 30 '13 at 17:34
1

Firstly - use pointers, secondly - do not forget to make your methods virtual.

Bartosz Marcinkowski
  • 6,651
  • 4
  • 39
  • 69
0

Your objects are being sliced, since you're storing a value type Player rather than a pointer.

Try this instead:

std::list<std::unique_ptr<Player>> playerList;
playerList.push_front(std::unique_ptr<Player>(new HumanPlayer(512,512, &playerList)));
Collin
  • 11,977
  • 2
  • 46
  • 60