Step 7 of 8
Composition over inheritance
Inheritance means is-a: a Pistol is a Weapon. For has-a relationships, use a member instead. That's composition:
class Squad : public std::vector<Player> { }; // wrong: a squad isn't a vector
class Squad { std::vector<Player> members_; }; // right: a squad has members
Why composition is the default in professional code:
- The class controls its own interface. Inheriting from
std::vectorwould exposeerase,clearand everything else, letting callers break your rules. - You can swap the member's type later without touching callers.
- Standard containers have no virtual destructor, so they aren't meant to be base classes at all.
Your turn: write class Squad that has a std::vector<std::string> of names, with a maximum size of 5:
bool add(const std::string& name): false if full or already in the squadbool remove(const std::string& name): false if not foundint size() const,std::string roster() const(names joined with", ", in join order)
Previous: Calling the base version, and protected Next: Challenge: program to an interface