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:
public:members can be used by anyone.private:members can only be used by the type's own member functions.
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
- Public interface first, private data last, so readers see what they can use.
- A trailing underscore (
target_) marks private data members in many codebases, avoiding clashes with method names liketarget(). - A method that only reads is marked
const(step 4 explains why).
Your task
Write a class Wallet with a private int money_ starting at 800, and public methods:
int money() constreturns itbool buy(int price)subtracts the price and returnstrueif there's enough money, otherwise changes nothing and returnsfalsevoid earn(int amount)adds money, but the total can never exceed 16000
Challenge 2
Write a class Ammo with a private magazine (starting at 30) and reserve (starting at 90), and public methods:
int mag() constandint reserve() constbool fire(): uses one bullet and returnstrue, or returnsfalseif the magazine is emptyvoid reload(): fills the magazine back to 30 from the reserve, as far as the reserve allows
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.