-1

I am having trouble finding the method to store instances of similar classes into a vector. I thought about using a base class, but I am not sure whether it will work. For example, using sports:

class player //base
{
   std::string name;
   int age;
   player(std::string name, int age) name (name), age (age);
};

class soccerplayer: public player
{
   float goal_per_game;
   //etc
};

class basketballplayer: public player
{
   float defensive_blocks;
   float three_pointers_per_game;
   //etc
};

class hockeyplayer: public player
{
   //etc
};

std::vector<player> favoriteplayers;

favoriteplayers.push_back(player("Lionel Messi", 33));

I am not sure if there is a method to store the various instances of this class. If not, what workaround is possible?

Enlico
  • 23,259
  • 6
  • 48
  • 102
Dave N.
  • 138
  • 1
  • 8
  • `std::vector` -- Look up [object slicing](https://stackoverflow.com/questions/274626/what-is-object-slicing), because that is what you will wind up doing if you use `std::vector`. – PaulMcKenzie May 07 '21 at 04:03
  • Does this answer your question? [How to store object of different class types into one container in modern c++?](https://stackoverflow.com/questions/59316961/how-to-store-object-of-different-class-types-into-one-container-in-modern-c) – anatolyg May 07 '21 at 04:13

1 Answers1

2

You can use a vector of (smart) pointers to the base class vs. a vector of values.

std::vector<std::unique_ptr<player> > favoriteplayers;

favoriteplayers.emplace_back(new sockerplayer(...));
favoriteplayers.emplace_back(new hockeyplayer(...));

All items in the vector point to the player base-class, but they can actually be objects of derived classes.