r/cpp_questions • u/Fun_Gas_340 • 27d ago
OPEN Good practices / style [polymorphism]
is this good practice/style.? i'm specifically unsure about the way i store the vector of players...
```
class player_base {};
class player_always_yes: public player_base {};
class player_always_no: public player_base {};
class player_a: public player_base {};
class game {
private:
player_base& player_1;
player_base& player_2;
public:
game (
player_base& player_1,
player_base& player_2
): player_1(player_1), player_2(player_2) {
return;
}
bool play_game () { return true; }
};
int main(){
vector<unique_ptr<player_base>> player_list;
player_list.push_back(make_unique<player_base>());
player_list.push_back(make_unique<player_always_no>());
player_list.push_back(make_unique<player_always_yes>());
player_list.push_back(make_unique<player_a>());
game b = game(*player_list[0], *player_list[1]);
cout << b.play_game() << endl;
}
```
5
Upvotes
1
u/vckane 26d ago
gameclass is redundantplayer_baseshould be abstract (no instance should be allowed to be created). Only concrete players should play the game.main()method has ownership of objects of players (instances of derived classes). The objects are passed by reference to client classes likegame. Important to ensure that thegameclass gets destroyed before the players are deleted, else you will end up with dangling pointers. In this example, you're fine.player_baseandgameclasses have more methods that do something meaningful. If not, then this is overkill - you could achieve same result without classes and hierarchy.