C++, lesson 10
As programs grow, loose variables become hard to keep consistent. A class bundles data with
the functions that work on it, and lets you decide which parts the rest of the program may
touch. C++ has two keywords for this, struct and class, and they differ only in the default
access: struct members are public unless you say otherwise, class members are private.
When a type is just a few values that travel together, with no rules about which combinations
are valid, a struct with public members is perfect:
An invariant is a rule that must always hold, such as "a bank balance never goes negative" or "a fraction's denominator is never zero". Make the data so only the class's own member functions can change it, and have every public function keep the rule true:
2 exercises to try what you just read.
privateA few things to notice:
: limit_{limit}, is the member initializer list; it
initializes members directly, before the body runs. Members are initialized in the order they
are declared in the class, whatever order you list them in.explicit stops the compiler from silently turning an int into a Counter.const after value() promises that the function doesn't change the object. Only const
member functions can be called on a const object or through a const&, so mark every
read-only member function const.count_ is a common naming convention for private members.For longer classes, declare members inside the class and define them below it with the class
name and :::
You can teach your types to work with operators. For a value type such as a point or a money
amount, +, == and << make code read naturally:
operator<< returns the stream so that calls can be chained. Only overload an operator when its
meaning is obvious; a + that deletes files would surprise everyone.
Write a Fraction class that always stores a fraction in lowest terms with a positive
denominator. Its constructor takes a numerator and a (non-zero) denominator and normalizes them:
divide both by their greatest common divisor (std::gcd from <numeric>), and if the
denominator is negative, flip the sign of both. Add operator+ and operator*, and an
operator<< that prints n/d, or just n when the denominator is 1.
Each input line is a/b op c/d where op is + or *. Print the result of each line.
Write a Thermostat class whose target temperature is always between 10 and 30 degrees
inclusive. Any request outside that range is clamped to the nearest limit.
explicit Thermostat(int start) sets the target (clamped).void up(int by), void down(int by) and void set(int value) change the target (clamped).int target() const returns it.int changes() const returns how many calls to up, down or set actually changed the
target.The first input value is the starting target. Then come commands up N, down N or set N
until the input ends. After each command print Target: <target>. At the end print
Changes: <count>.
struct Song {
std::string title;
int seconds{0}; // default member initializer
};
Song s{"Blue", 215};
std::cout << s.title << " lasts " << s.seconds << "s\n";class Counter {
public:
explicit Counter(int limit) : limit_{limit} {}
void click() {
if (count_ < limit_) {
++count_;
}
}
int value() const { return count_; }
private:
int limit_;
int count_{0};
};
Counter people{3};
people.click();
std::cout << people.value() << '\n'; // 1
// people.count_ = 99; // error: count_ is privateclass Timer {
public:
void add(int seconds);
private:
int total_{0};
};
void Timer::add(int seconds) {
total_ += seconds;
}struct Money {
long long cents{0};
};
Money operator+(Money a, Money b) {
return Money{a.cents + b.cents};
}
std::ostream& operator<<(std::ostream& out, Money m) {
return out << m.cents / 100 << '.' << (m.cents % 100 < 10 ? "0" : "") << m.cents % 100;
}
std::cout << Money{150} + Money{275} << '\n'; // 4.25Input:
1/2 + 1/3
2/4 * 4/6
3/-4 + 1/4
Output:
5/6
1/3
-1/2Input:
21
up 3
up 10
set 30
down 25
Output:
Target: 24
Target: 30
Target: 30
Target: 10
Changes: 3