This problem uses classes and static members. You may leave it until after the object-oriented programming lecture.
A Quota tracks an allowance and how much has been used. Its contract is:
- Each object keeps the allowance it had when constructed. With no constructor argument, it uses the current default. Explicit constructor arguments are nonnegative and supply the allowance directly.
set_default(n)changes the default for future objects. It rejects negative values without changing that default.take(n)uses n units if enough remain, returning true. Otherwise it returns false without changing the object. Negative requests fail.reset()clears the used amount and keeps that object's allowance;remaining()reports how much is left.
A developer submits the following patch for review. The original code meets the contract. In a diff, - marks removed lines and + marks added lines; unmarked lines provide context. assert(condition) fails a test if the condition is false.
--- a/Quota.h +++ b/Quota.h @@ -1,30 +1,33 @@ #ifndef QUOTA_H #define QUOTA_H class Quota { - int limit_; + int explicit_limit_; int used_; static int& default_limit() { static int limit = 10; return limit; } + int limit() const { + return explicit_limit_ < 0 ? default_limit() : explicit_limit_; + } public: - Quota() : Quota(default_limit()) {} - explicit Quota(int limit) : limit_(limit), used_(0) {} + Quota() : Quota(-1) {} + explicit Quota(int limit) : explicit_limit_(limit), used_(0) {} static bool set_default(int limit) { if (limit < 0) return false; default_limit() = limit; return true; } void reset() { used_ = 0; } bool take(int n) { - if (n < 0 || n > limit_ - used_) return false; + if (n < 0 || n > limit() - used_) return false; used_ += n; return true; } - int remaining() const { return limit_ - used_; } + int remaining() const { return limit() - used_; } }; #endif --- a/tests.cpp +++ b/tests.cpp @@ -23,9 +23,9 @@ assert(unchanged_default.remaining() == 5); Quota explicit_limit(3); assert(explicit_limit.remaining() == 3); assert(Quota::set_default(10)); changed_default.reset(); - assert(changed_default.remaining() == 5); + assert(changed_default.remaining() == 10); std::cout << "quota tests passed\n"; }
