C/C++ Arena

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:

Previous: Member initializer lists Next: Challenge: a Fraction class