Methods That Change the Object
A method can change the members of its object too. In a game, the hero takes damage, and her health goes down. That's a job for a method:
#include <iostream>
#include <string>
struct Hero {
std::string name;
int health;
void takeDamage(int amount) {
health -= amount;
}
void printStatus() {
std::cout << name << ": health " << health << std::endl;
}
};
int main() {
Hero aria = {"Aria", 100};
aria.takeDamage(30);
aria.takeDamage(25);
aria.printStatus();
return 0;
}This prints:
Aria: health 45A method can have parameters, like any function: amount is how much health the hero loses. The health itself needs no parameter, because the method changes the object it was called on, here aria.
Compare it with a function outside the struct, void takeDamage(Hero& hero, int amount). There, you have to pass the hero by reference, or the function changes a copy. A method doesn't need the &: it always works on the object itself, never on a copy.
But why write a method for a single subtraction? Because a game has rules. Health shouldn't drop below 0: a hero with -30 health makes no sense, and no health bar can show it. When every place in the program that hurts the hero calls takeDamage, the rule has to be written only once, in the method:
void takeDamage(int amount) {
health -= amount;
if (health < 0) {
health = 0;
}
}Without the method, you would have to remember the condition at every aria.health -= … in the program, and forgetting it once would be enough for a bug.
Instructions
- 1
Add a method
takeDamage(int amount)to the structHero, which lowers the hero's health byamount. At the end ofmain(beforereturn 0;), Aria takes30damage: call the method, and print her status again. The program printsAria: health 100and thenAria: health 70. Keep the line that creates Aria as it is: the exercise will also try other values. - 2
A troll hits Aria hard. Add the rule to
takeDamage: the health never drops below 0. Then let Aria take90more damage and print her status once more. The last line isAria: health 0.