Learn/C++/10. Structuring data with classes
Lesson 10 of 15
Sign in

C++, lesson 10

Structuring data with classes

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.

Plain structs for plain data

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:

Classes protect invariants

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.

Exercise 1

Fraction calculator

Press Ctrl Enter or Check to test your code.

Exercise 2

Thermostat

Press Ctrl Enter or Check to test your code.

private

A few things to notice:

  • The constructor has the class's name and no return type. It runs when an object is created. The part after the colon, : 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.
  • The trailing underscore on count_ is a common naming convention for private members.

Member functions defined outside

For longer classes, declare members inside the class and define them below it with the class name and :::

Operator overloading

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.

Further reading

  • cppreference: Classes
  • cppreference: Access specifiers
  • cppreference: Constructors and member initializer lists
  • cppreference: Operator overloading
  • cppreference: std::gcd

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 private
class 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.25
Input:
1/2 + 1/3
2/4 * 4/6
3/-4 + 1/4
Output:
5/6
1/3
-1/2
Input:
21
up 3
up 10
set 30
down 25
Output:
Target: 24
Target: 30
Target: 30
Target: 10
Changes: 3