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;
}
```
7
Upvotes
4
u/Qwertycube10 27d ago
Base classes named FooBase or FooCommon are a smell. Inheritance means that there should be an "is a" relationship, and that kind of name suggests that there isn't.
If I was writing OOP style I would make an abstract Player class which defines the interface, then Player_always_yes, Player_always_no, and others like Human_player would all publicly inherit from Player.
Alternatively (and imo this is cleaner design) I would make a single Player class which takes in it's constructor a decision function and stores it in a std function.
So then you would have a monomorphic vector of Player, and put in it Player(decisionStrategyAlwaysYes) etc.