Codiqo

Learn C++ · lesson 40 of 61 · about 8 minutes

Encapsulation

Protect the hero's shield: keep data private, expose safe member functions, and protect the object's rules.

What you'll learn

  • Make data private
  • Add getters and validated setters
  • Mark read-only functions const

The hero's shield

The hero's shield starts at 100 durability. Each blow it blocks takes off half the damage, and the smith can repair it for 10 gold, but never past 100. If the durability were public, any line of the program could set it to 500 or -20. So it's private, and the only ways to change it are block() and repair(), which keep it between 0 and 100. durability() and broken() let the rest of the adventure read it, and they're const because they only look.

Protect the rules

If anyone can write account.balance = -1000;, the class can't keep its promises. Encapsulation means hiding data behind member functions that check the rules:

  • data members are private
  • public functions read them (getters, marked const) and change them safely

A thermostat that stays in range

#include <iostream>

class Thermostat {
public:
    explicit Thermostat(int t) { set(t); }

    void set(int t) {
        if (t < 10) t = 10;
        if (t > 30) t = 30;
        temp_ = t;
    }

    int temp() const { return temp_; }

private:
    int temp_ = 20;
};

int main() {
    Thermostat t(45);
    std::cout << t.temp() << "\n";
    t.set(5);
    std::cout << t.temp() << "\n";
}

Output

30
10

Tip

A trailing underscore (temp_) is a common way to mark private members, so the getter can be called temp().

Functions that answer questions

A getter doesn't have to hand back a member as it is. empty() answers a question about the object, so the rest of the program never needs to know how the battery stores its charge, and use() returns whether it worked instead of letting the charge go below 0.

A battery that says when it's empty

#include <iostream>

class Battery {
public:
    bool use(int amount) {
        if (amount > charge_) return false;
        charge_ -= amount;
        return true;
    }

    bool empty() const { return charge_ == 0; }

private:
    int charge_ = 50;
};

int main() {
    Battery b;
    std::cout << std::boolalpha << b.use(30) << " " << b.use(30) << " " << b.use(20) << "\n";
    std::cout << b.empty() << "\n";
}

Output

true false true
true

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.