10.5 — Keeping data safe (encapsulation)

📘 Chapter 10⏱ about 1 min read✍️ Beginner friendly
Read one box at a time. No rush.

Why private?#

If anyone can change a member, anyone can break it:

C++ — wrong ✗
struct Account{    double balance {};}; Account a {};a.balance = -1000000;   // oops, nothing stops this

Guard the data#

Make data private, and only allow changes through functions that check the rules:

C++ — right ✓
class Account{public:    void deposit(double amount)    {        if (amount > 0)            m_balance += amount;    }     bool withdraw(double amount)    {        if (amount <= 0 || amount > m_balance)            return false;   // not allowed        m_balance -= amount;        return true;    }     double balance() const { return m_balance; } private:    double m_balance { 0.0 };};

Now the balance can never go below zero. The class protects its own rules.

Encapsulation

Hiding an object's data and only allowing access through its functions. It keeps objects in a valid state and lets you change the inside later without breaking other code.

Getters and setters#

  • A getter reads a value: balance().
  • A setter changes a value (usually with checks): deposit().
Good habit

Keep data members private. Give a class the smallest set of public functions that does the job.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.