C/C++ Arena

Step 2 of 9

public and private

With a plain struct, any code anywhere can change any member. If an account's balance must never go negative, nothing stops acct.balance = -500; from some far-away function. C++ lets a type protect its data with access specifiers:

A class is exactly a struct whose members are private by default (a struct's are public by default). By convention, class is used for types that protect their data.

#include <iostream>

class Thermostat {
public:
    void set(int degrees) {
        if (degrees < 10) degrees = 10;
        if (degrees > 30) degrees = 30;
        target_ = degrees;
    }
    int target() const { return target_; }

private:
    int target_ = 20;
};

int main() {
    Thermostat t;
    t.set(45);
    std::cout << t.target() << "\n";
    t.set(18);
    std::cout << t.target() << "\n";
}
30
18

Why this matters

Outside code can't write t.target_ = 45; (it's a compile error: 'target_' is a private member of 'Thermostat'). The only way to change the temperature is through set, which enforces the 10 to 30 rule. The rule lives in one place, so it can't be broken by accident anywhere in a million-line program. This is encapsulation, the central idea of classes.

Conventions

Your task

Write a class Wallet with a private int money_ starting at 800, and public methods:

Challenge 2

Write a class Ammo with a private magazine (starting at 30) and reserve (starting at 90), and public methods:

Challenge 3

Write a class Streak that tracks kill streaks: void kill() adds one to the current streak, void death() resets it to 0, int current() const returns it, and int best() const returns the longest streak ever reached. Keep the data private.

Previous: Member functions Next: Constructors