#include /****************************************************** * Suppose you require a counter in a program, but by * design its value should only ever increase by one. * * For example, suppose you are creating an accounting * system in which transactions must be counted * one-at-a-time for taxation purposes. There is no * reason for a programmer using this counter to either * decrement the count or assign an arbitrary value to * it. * * To prevent users from directly changing the member * variable 'counter_', it is declared under 'private:'. * * Instead, the class provides two member functions: * * increment() - increment the counter by one * value() - query the current value * * Thus, the class controls how the value of the counter * can be changed. * * NOTE: This does not provide security. It instead * helps prevent a programmer from accidentally * using the object incorrectly. * * Looking ahead: After the next topic on operator * overloading, we will see how we can * modify this class to use operators * instead of .increment() and .value(). ******************************************************/ // Class declaration class Increment_only_counter; // Function declaration int main(); // Class definition class Increment_only_counter { public: Increment_only_counter(); void increment(); unsigned int value() const; private: unsigned int counter_; }; // Function definition int main() { Increment_only_counter a{}; std::cout << "Initially, the counter is " << a.value() << "." << std::endl; for ( int k{17}; k <= 1532; ++k ) { if ( k%17 == 0 ) { a.increment(); } } std::cout << "There are " << a.value() << " numbers divisible by 17 between " << "17 and 1532, inclusive." << std::endl; return 0; } // Member function definitions // Construct an increment-only counter whose initial // value is zero. Increment_only_counter::Increment_only_counter(): counter_{ 0 } { // Empty constructor } // Increment the counter by one. void Increment_only_counter::increment() { ++counter_; } // Return the current value of the counter. unsigned int Increment_only_counter::value() const { return counter_; }