Rules in One Place
The hero takes damage, so she needs healing too. Healing has a rule of its own: it can't raise the health above the hero's maximum, which is the health she started with. So the class remembers the maximum in one more private member, and the constructor stores the starting health in both:
#include <iostream>
#include <string>
class Hero {
private:
std::string name;
int health;
int maxHealth;
public:
Hero(std::string heroName, int startHealth) {
name = heroName;
health = startHealth;
maxHealth = startHealth;
}
void takeDamage(int amount) {
health -= amount;
if (health < 0) {
health = 0;
}
}
void heal(int amount) {
health += amount;
if (health > maxHealth) {
health = maxHealth;
}
}
void printStatus() const {
std::cout << name << ": health " << health << std::endl;
}
};
int main() {
Hero aria("Aria", 100);
aria.takeDamage(30);
aria.heal(50);
aria.printStatus();
return 0;
}Aria loses 30 health and drinks a potion that heals 50, but only 30 of it fits below her maximum. The program prints:
Aria: health 100Look at what the class does now: all the rules about health are inside it. takeDamage keeps the health at 0 or above, and heal at the maximum or below. Because health is private, no other code can break these rules. When the health is wrong, you know where to look, and when a rule changes, you change it in one place, and the whole game follows. Programmers call this encapsulation: the data and the rules that keep it right are together in a class, and the data is hidden from the rest of the program.
A method can also call the other methods of its object, just by their names, without an object and a dot. In the task, for example, isAlive() inside heal asks whether the same hero is alive, the one that heal was called on.
Instructions
- 1
Add the private member
maxHealth, and in the constructor, store the starting health in it. Then write the methodheal(int amount), which addsamountto the health, but never above the maximum. At the end ofmain, heal Aria by20and print her status. The program printsAria: health 70and thenAria: health 90. Keep the line that creates Aria and the line witharia.takeDamage(30);as they are: the exercise will also try other values. - 2
A fallen hero can't be healed. Change
healso that it does nothing when the hero isn't alive; you can callisAlive()in it. Then, at the end ofmain, a dragon hits Aria for200, and you try to heal her by50. Print her status once more:Aria: health 0.