Private and Public Members
The rule in takeDamage holds only as long as everyone uses the method. Nothing stops a line such as aria.health -= 500; in main, and the hero suddenly has -430 health. In a small program you would notice. But a game has thousands of lines, often written by several people, and sooner or later somebody changes the health directly.
C++ can forbid that. Write class instead of struct, and divide the type into two parts:
class Hero {
private:
std::string name = "Aria";
int health = 100;
public:
void takeDamage(int amount) {
health -= amount;
if (health < 0) {
health = 0;
}
}
void printStatus() {
std::cout << name << ": health " << health << std::endl;
}
};Everything below private: is private: only the methods of the class itself can use it. Everything below public: is public: the whole program can use it. Note the colon after both words. Now main can call aria.takeDamage(500), but the line aria.health -= 500; doesn't compile. The error says error: 'health' is a private member of 'Hero', and a note below it, note: declared private here, points to where the member is. The compiler now makes sure the rule holds: the only way to change the health is through the methods, and they keep it at 0 or above.
A type made with class is a class, and its variables are objects, as with structs. For what this course does, struct and class differ only in what you get without private: and public:: in a struct, everything is public, and in a class, everything is private. Programmers use structs for simple data that anyone may change, and classes for types that have rules to protect. This course writes the private members first and the public methods after them.
Private members can't be filled in from outside, so braces don't work any more: Hero aria = {"Aria", 100}; ends with the error no matching constructor for initialization of 'Hero'. That's why this hero gets default values, and Hero aria; creates it with them. Soon you'll learn a better way, the constructor that the error message mentions.
Instructions
- 1
The program prints
Aria: health 70and thenAria: health -430, becausemainchanges the health directly. Replace the linearia.health -= 500;with a call oftakeDamagethat takes the same 500 health. The last line is nowAria: health 0. Keep the line withint health = 100;as it is: the exercise will also try other values. - 2
So that this can't happen again, turn
Herointo a class: writeclassinstead ofstruct, put the two members belowprivate:and the two methods belowpublic:. The program prints the same as before. Then try writingaria.health -= 500;back intomain, look at the error, and delete the line again.