Step 8 of 9
Keeping invariants
An invariant is a rule that must be true for every object, at all times, from the outside. For a health bar: 0 <= hp <= max.
This is the real reason for private: if only member functions can touch the data, only they can break the rule, and you check it in one place. Every constructor must establish the invariant and every member function must preserve it.
void damage(int amount) {
hp_ = std::max(0, hp_ - amount); // never below 0
}
Your turn: write class Health:
Health(int max): max below 1 becomes 1; starts fullvoid damage(int n)andvoid heal(int n): negative amounts are ignored; hp stays within0..maxint hp() const,int max() const,bool alive() const
Previous: Member initializer lists Next: Challenge: a Fraction class