A private member is useful when not every value makes sense. A prepaid balance should never become negative. A condition that must remain true for every valid object is called an invariant. Here the invariant is cents >= 0.
The constructor establishes a valid starting state. Public operations must preserve it; private blocks direct outside writes but does not make the class's own code correct automatically. A withdrawal can report success with a bool: return false before changing anything when the amount is invalid, or update the balance and return true when it is allowed. This makes failure an ordinary result that the caller can inspect.
Check before changing the member. Subtracting first and checking afterward would briefly create an invalid state and require recovery. Reject negative amounts too: subtracting a negative number would add credit rather than spend it. Zero is allowed here and leaves the balance unchanged.
#include <iostream>
class Seats {
private:
int available = 6;
public:
bool reserve(int requested) {
if (requested < 0 || requested > available) { return false; }
available -= requested;
return true;
}
int left() { return available; }
};
int main() {
Seats hall;
std::cout << hall.reserve(8) << ' ' << hall.left() << '\n';
}
The example prints 0 6: the reservation fails and all six seats remain available. In the editor, the constructor already replaces a negative starting balance with zero. Your work is in spend. Put the rejection guard first so invalid requests leave immediately; the subtraction belongs after it, on the path that reaches the supplied return true. Each test call uses a fresh wallet, so a rejected request cannot affect the later accepted payment.
The diagram applies the same check-before-change rule to a bounded counter rather than a wallet. Its limits differ, but the role of the public operation is the same.
This separate counter starts at zero. Only the accepted path is shown: add(n) checks n >= 0 && n <= 100 - count before changing private state. A rejected request must leave the count unchanged.
spend: return false if amount is negative or exceeds cents. Both rejected calls must leave the balance at 500.amount from cents after the guard. The successful payment should report Paid: 1 375.Edit main.cpp, then press Run to inspect the Console. Press Submit to check your work. Keep the supplied probes in place.