Lesson 8 of 10
Structs
- 13 min
- 5 checks
- 3 hints
- Go to task
Goal
A struct with its fields and member functions
Explanation
A struct groups related data under one name. A player has a name and health, so instead of defining two separate variables for every player, you write struct Player { std::string name; int hp = 100; };, and don't forget the semicolon after the closing brace. You create a player by listing the values in the order of the fields, like Player hero{"Layan", 80};, and any field you leave out takes its default value, so the player Player hero{"Layan"}; has 100 HP. You reach the fields with a dot, as in hero.hp -= 10;.
You can also write functions inside the struct that work on its fields directly. These are called member functions: inside takeDamage, hp means this player's own health, and you call it with a dot, as in hero.takeDamage(30);. The word const after the parentheses in bool alive() const is a promise that the function doesn't change the object, and on a const Player& you can only call functions that make this promise. So a function that reads the team as const std::vector<Player>& can't call alive() unless it's const.
The benefit is that the rule stays with the data: health never drops below zero, because damage goes through takeDamage, which prevents it. But the fields of a struct are exposed, and nothing stops code outside it from writing hero.hp = -50;. That's what the next lesson deals with.
Your task
Complete Player so its health starts at 100 when it isn't given, and make void takeDamage(int amount) reduce the health without ever taking it below zero, ignoring negative damage so it never adds health. Make bool alive() const return true as long as the health is above zero. Then complete int aliveCount(const std::vector<Player>& team) so it returns how many players on the team are alive.
Checks
5 checks- A Player can be created from a name and has 100 HP if none is given
- takeDamage reduces the health
- takeDamage never takes the health below zero, and negative damage doesn't raise it
- alive returns true as long as the health is above zero
- aliveCount counts the players on the team who are alive