Encapsulation

Encapsulation in C++: A cash machine holds money, a card reader, a printer and a ledger. Its interface is four buttons and a slot.

The Analogy: The Cash Machine

A cash machine holds money, a card reader, a printer and a ledger. Its interface is four buttons and a slot. You cannot reach in and set the balance, because if you could, the machine's one promise — the ledger always matches the cash in the drawer — would be worthless.

That promise is an invariant: a statement about the object that is true before and after every operation. Encapsulation is not "make the fields private". It is: decide what your class promises, then make it impossible for anyone, including yourself in six months, to break that promise from outside. Privacy is the tool; the invariant is the point.

The previous lesson covered the mechanics of public, protected and private. This one is about deciding what to put behind them.


Syntax or Core Structure

Compare two classes holding the same data.

#include <iostream>
#include <string>
#include <vector>

// --- Encapsulated in name only. Every field has a getter and a setter,
//     so the class enforces nothing at all.
class WeakBasket {
    std::vector<double> prices;
    double total{0.0};
public:
    std::vector<double>& getPrices() { return prices; }   // hands out the internals
    double getTotal() const { return total; }
    void setTotal(double t) { total = t; }                // total can now be a lie
};

// --- Genuinely encapsulated. The invariant is
//     "total always equals the sum of prices".
class Basket {
    std::vector<double> prices;
    double total{0.0};
public:
    void add(double price) {
        if (price < 0.0) { return; }
        prices.push_back(price);
        total += price;                     // both change together, always
    }

    bool removeLast() {
        if (prices.empty()) { return false; }
        total -= prices.back();
        prices.pop_back();
        return true;
    }

    double getTotal() const { return total; }
    std::size_t count() const { return prices.size(); }
};

int main() {
    WeakBasket w;
    w.getPrices().push_back(10.0);          // added a price...
    std::cout << w.getTotal() << "\n";      // 0 -- total is now wrong
    w.setTotal(-999.0);                     // and nothing stops this

    Basket b;
    b.add(10.0);
    b.add(5.50);
    b.add(-3.0);                            // rejected
    std::cout << b.getTotal() << " " << b.count() << "\n";   // 15.5 2
    return 0;
}

WeakBasket has private members and is not encapsulated. getPrices() returning a non-const reference makes prices public in all but name, and setTotal lets a caller contradict it.


Technical Depth: Designing the Boundary

Start from the invariant, not the fields

Before writing a single member, finish this sentence: "For any object of this class, it is always true that..." Everything else follows.

ClassInvariantWhat that forbids
Baskettotal equals the sum of pricesWriting total from outside
Dateday is valid for month and yearSetting day to 31 in February
Playlistposition < tracks.size()Erasing a track without fixing position
FileWriterThe handle is open or null, never danglingCopying the handle carelessly

A class with no invariant does not need encapsulation. A Point{x, y} where any two doubles are valid is honestly a struct with public members, and wrapping it in getters adds noise without adding safety.

The getter/setter reflex is not encapsulation

class Person {
    int age;
public:
    int getAge() const { return age; }
    void setAge(int a) { age = a; }          // exactly as open as 'public int age'
};

If every field has a matching pair, you have written a public struct with extra typing. A setter earns its place only when it does something: validate, convert, notify, or keep another member in step.

void setAge(int a) {
    if (a < 0 || a > 130) { throw std::invalid_argument("implausible age"); }
    age = a;
}

Tell, do not ask

Prefer moving behaviour into the class over pulling data out of it.

// Asking: the caller knows the rules, so every caller must know them.
if (account.getBalance() >= amount && !account.getFrozen()) {
    account.setBalance(account.getBalance() - amount);
}

// Telling: the rules live in one place.
account.withdraw(amount);

The second version can never be got wrong at a call site, and the rule can be changed once.

Do not leak references to internals

Returning a handle to a private member undoes the encapsulation silently:

class Order {
    std::vector<Item> items;
public:
    std::vector<Item>& all() { return items; }              // leaks: caller can clear()
    const std::vector<Item>& all() const { return items; }  // safe to read
    std::vector<Item> copy() const { return items; }        // safest, costs a copy
};

Better still, expose the operations callers actually need — begin()/end() for iteration, size(), at() — so the container type itself remains an implementation detail you can change later.

Const correctness is part of the boundary

A const method is a public promise that calling it cannot change the object. That promise is what lets callers share objects freely, cache results, and reason about threading. An accessor that forgets const forces every caller to hold a mutable reference for no reason.

Encapsulation buys you the freedom to change

This is the practical payoff. Basket above stores a std::vector<double> and a running total. Because neither is visible, you may switch to computing the total on demand, or to a std::deque, or add a currency field — and not one caller needs editing. In WeakBasket, getPrices() has welded std::vector<double> into the public interface forever.

Hiding the implementation completely: pimpl

In a header, private members are still visible to the compiler, so changing one recompiles every file that includes it. The pointer-to-implementation idiom moves them out of sight:

// widget.h -- callers see no members at all
class Widget {
    class Impl;                             // declared, not defined
    std::unique_ptr<Impl> impl;
public:
    Widget();
    ~Widget();                              // must be defined in the .cpp
    void draw() const;
};

The cost is one indirection and a heap allocation per object. Use it for library boundaries and slow-building headers, not for everyday classes.

Strong types push validation to the type system

The strongest form of encapsulation makes an invalid value unrepresentable rather than merely rejected:

class Percentage {
    double value;                       // invariant: 0 <= value <= 100
public:
    explicit Percentage(double v) : value(v) {
        if (v < 0.0 || v > 100.0) { throw std::out_of_range("0-100 only"); }
    }
    double asFraction() const { return value / 100.0; }
};

void applyDiscount(Percentage p);       // cannot be called with 150 by accident

A function taking Percentage needs no validation of its own — the type has already done it, once, at the boundary.


Real World Example: A Seat Reservation Map

An invariant with real teeth: the number of seats marked sold always equals soldCount, and no seat is ever sold twice.

#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>

// A strong type: a row/seat pair that cannot be built out of range.
class SeatId {
    int row;
    int number;
public:
    SeatId(int r, int n) : row(r), number(n) {
        if (r < 1 || r > 20 || n < 1 || n > 10) {
            throw std::out_of_range("seat outside the auditorium");
        }
    }
    int rowIndex() const { return row - 1; }
    int seatIndex() const { return number - 1; }
    std::string label() const {
        return std::string(1, static_cast<char>('A' + row - 1)) +
               std::to_string(number);
    }
};

class Auditorium {
    // Invariant: soldCount == the number of true entries in 'sold'.
    std::vector<bool> sold;
    std::size_t soldCount{0};
    std::size_t rows;
    std::size_t perRow;

    // Private: the storage layout is nobody else's business.
    std::size_t indexOf(const SeatId& seat) const {
        return static_cast<std::size_t>(seat.rowIndex()) * perRow +
               static_cast<std::size_t>(seat.seatIndex());
    }

public:
    Auditorium(std::size_t rowCount, std::size_t seatsPerRow)
        : sold(rowCount * seatsPerRow, false), rows(rowCount), perRow(seatsPerRow) {}

    // Commands: each keeps both members in step, or does nothing.
    bool reserve(const SeatId& seat) {
        const std::size_t i = indexOf(seat);
        if (sold[i]) { return false; }              // already gone
        sold[i] = true;
        ++soldCount;                                // never drifts from 'sold'
        return true;
    }

    bool release(const SeatId& seat) {
        const std::size_t i = indexOf(seat);
        if (!sold[i]) { return false; }
        sold[i] = false;
        --soldCount;
        return true;
    }

    // Tell, do not ask: the caller states intent, the class finds the seats.
    std::vector<SeatId> reserveBlock(int row, int howMany) {
        std::vector<SeatId> taken;
        for (int n = 1; n <= static_cast<int>(perRow) && howMany > 0; ++n) {
            const SeatId candidate{row, n};
            if (reserve(candidate)) { taken.push_back(candidate); --howMany; }
        }
        if (howMany > 0) {                           // could not satisfy the request
            for (const SeatId& s : taken) { release(s); }   // all or nothing
            return {};
        }
        return taken;
    }

    // Queries: const, and none of them hands out a reference to 'sold'.
    bool isSold(const SeatId& seat) const { return sold[indexOf(seat)]; }
    std::size_t soldSeats() const { return soldCount; }
    std::size_t capacity() const { return rows * perRow; }
    std::size_t freeSeats() const { return capacity() - soldCount; }
    double occupancy() const {
        return 100.0 * static_cast<double>(soldCount) /
               static_cast<double>(capacity());
    }
};

int main() {
    Auditorium hall{5, 8};                          // 40 seats

    std::cout << hall.reserve(SeatId{1, 1}) << "\n";     // 1
    std::cout << hall.reserve(SeatId{1, 1}) << "\n";     // 0 -- no double sale
    std::cout << hall.soldSeats() << "\n";               // 1

    const std::vector<SeatId> family = hall.reserveBlock(2, 4);
    for (const SeatId& s : family) { std::cout << s.label() << " "; }
    std::cout << "\n";                                   // B1 B2 B3 B4

    const std::vector<SeatId> impossible = hall.reserveBlock(3, 20);
    std::cout << impossible.size() << " " << hall.soldSeats() << "\n";  // 0 5

    std::cout << hall.freeSeats() << " free, "
              << hall.occupancy() << "% full\n";          // 35 free, 12.5% full

    try {
        hall.reserve(SeatId{99, 1});                      // rejected by SeatId
    } catch (const std::out_of_range& e) {
        std::cout << "rejected: " << e.what() << "\n";
    }
    return 0;
}

The invariant drives every line. sold and soldCount are both private and are only ever changed inside reserve and release, which each touch both in the same breath — that is the only reason soldSeats() can be trusted, and it is why there is no setSoldCount. No method returns a reference to sold, so the storage really is a free choice: swapping std::vector<bool> for a bitset or a std::set of sold indices would not change one caller. indexOf is private because the row-major layout is an implementation detail; publishing it would let callers compute indices themselves and then the layout could never change. SeatId is a strong type doing validation once, at construction, which is why reserve contains no range check at all and hall.reserve(SeatId{99, 1}) fails before Auditorium is even involved — an int, int parameter pair would have pushed that check into every method instead. reserveBlock is the tell-don't-ask case: a caller asking "which seats are free in row 2?" and reserving them itself would race and would duplicate the all-or-nothing rule, so the class takes the intent and rolls back its own partial reservations on failure, which is exactly why soldSeats() still reads 5 after the impossible request. And every query is const, so a report function can take const Auditorium& and be structurally incapable of selling a ticket.


Common Mistakes

  1. Believing private fields plus getters and setters equals encapsulation. If every field has a pair, the class enforces nothing.
  2. Returning a non-const reference to a private container. getItems() returning std::vector<Item>& lets a caller clear() it.
  3. Splitting one invariant across two setters. setPrices and setTotal cannot both be safe; there must be one operation that changes both.
  4. Leaving a class with no invariant wrapped in accessors. For a plain Point, a struct is more honest.
  5. Asking instead of telling. Pulling three values out to compute a decision means every caller re-implements the rule.
  6. Forgetting const on queries, which forces callers to hold mutable references and blocks const& parameters.
  7. Validating in every method instead of once at the boundary. A strong type does it once.
  8. Exposing the container type in the public interface, which freezes an implementation choice permanently.
  9. Reaching for pimpl everywhere. It costs an allocation and an indirection; save it for library headers.

Best Practices

  • Write the invariant down first, as a comment above the private members. Everything else is derived from it.
  • Expose operations, not fields. Name them for what the caller wants to achieve.
  • Add a setter only when it does real work — validate, convert, notify, or update a sibling member.
  • Return by value or const&, and prefer exposing size(), at(), begin()/end() over the container itself.
  • Mark every query const.
  • Make invalid states unrepresentable with a strong type, so validation happens once.
  • Keep the public interface as small as it can be — you can always add to it, but you can never quietly remove.
  • Restore the invariant before every method returns, including on the failure paths.
  • Use a struct with public members when there genuinely is no invariant.

Practice Exercises

  1. Find the leak: Add std::vector<double>& prices() to Basket, then use it from main to push a price directly and print getTotal(). Show the total is now wrong, remove the method, and describe in a comment what invariant you restored.
  2. Kill the setters: Take a Rectangle with setWidth, setHeight, getWidth, getHeight and getArea, and redesign it so its only mutating operations are scale(double) and resize(double, double) — both rejecting non-positive values. List which previously-possible mistakes are now impossible.
  3. Strong type: Write a Rating class wrapping an int from 1 to 5 that throws otherwise, then a double averageRating(const std::vector<Rating>&) containing no validation at all. Explain in a comment why none is needed.
  4. Invariant under failure: Add a reserveBlock variant to Auditorium that returns partial results instead of rolling back. Reserve an impossible block, then verify soldSeats() against the seats you can actually see as sold, and say which version you would ship.