TExcelTAD
Home › C++ › C++ Encapsulation

C++ Encapsulation

Encapsulation means bundling data with the code that works on it, and hiding the data so it can only be changed in controlled ways. The outside world talks to the object through a small public interface; the internal representation stays private.

Why hide data?

Every class has rules that must always hold — its invariants. A Fraction must never have a zero denominator; a BankAccount must never have a negative balance; a Date must never be "February 30". If the data is public, any line of code anywhere can break these rules. If it is private, only the class's own methods can change it, so you only need to get the rules right in one place.

Getters and setters

The classic pattern is a private attribute with a public getter (reads it) and an optional setter (validates and writes it):

cpp · try it yourself
#include <iostream>
#include <string>
using namespace std;

class Employee {
public:
    Employee(string name, double salary) : name_(name) {
        setSalary(salary);
    }

    const string& name() const { return name_; }   // getter
    double salary() const { return salary_; }      // getter

    void setSalary(double s) {                     // setter with validation
        if (s < 0) {
            cout << "Invalid salary for " << name_ << ", using 0\n";
            s = 0;
        }
        salary_ = s;
    }

private:
    string name_;
    double salary_ = 0;
};

int main() {
    Employee e("Rosa", 52000);
    e.setSalary(55000);
    cout << e.name() << " earns " << e.salary() << "\n";

    Employee bad("Ghost", -10);
    cout << bad.name() << " earns " << bad.salary() << "\n";
}
Rosa earns 55000
Invalid salary for Ghost, using 0
Ghost earns 0

Notice the absence of a setName method: the name is effectively read-only after construction. Encapsulation lets you decide exactly which changes are allowed.

Prefer behaviour over setters

Blindly adding a getter and setter for every field is not real encapsulation — it is a public field with extra steps. A better design exposes meaningful operations:

cpp · try it yourself
#include <iostream>
#include <stdexcept>
using namespace std;

class BankAccount {
public:
    explicit BankAccount(double opening) : balance_(opening) {}

    void deposit(double amount) {
        if (amount <= 0) throw invalid_argument("deposit must be positive");
        balance_ += amount;
    }

    bool withdraw(double amount) {
        if (amount <= 0 || amount > balance_) return false;
        balance_ -= amount;
        return true;
    }

    double balance() const { return balance_; }

private:
    double balance_;
};

int main() {
    BankAccount acc(100);
    acc.deposit(40);
    cout << boolalpha;
    cout << "withdraw 30: " << acc.withdraw(30) << "\n";
    cout << "withdraw 500: " << acc.withdraw(500) << "\n";
    cout << "balance: " << acc.balance() << "\n";
}
withdraw 30: true
withdraw 500: false
balance: 110

There is no setBalance — and there never should be. The only ways to change the balance are the operations that make sense for a bank account.

Changing the inside without breaking the outside

Because users only see the public interface, you can change the internal representation freely. This Temperature class stores Kelvin internally, but callers think in Celsius and Fahrenheit:

cpp · try it yourself
#include <iostream>
using namespace std;

class Temperature {
public:
    static Temperature fromCelsius(double c)    { return Temperature(c + 273.15); }
    static Temperature fromFahrenheit(double f) { return Temperature((f - 32) * 5 / 9 + 273.15); }

    double celsius() const    { return kelvin_ - 273.15; }
    double fahrenheit() const { return celsius() * 9 / 5 + 32; }

private:
    explicit Temperature(double k) : kelvin_(k) {}
    double kelvin_;          // could be changed to store Celsius without affecting users
};

int main() {
    Temperature boiling = Temperature::fromCelsius(100);
    Temperature body = Temperature::fromFahrenheit(98.6);
    cout << boiling.fahrenheit() << "\n";
    cout << body.celsius() << "\n";
}
212
37

Even the constructor is private here: objects can only be made through the clearly named factory functions.

Benefits at a glance

Benefit How encapsulation helps
Correctness Invariants are checked in one place
Maintainability Internals can change without touching calling code
Readability The public interface documents how the class is meant to be used
Debugging If the data is wrong, only a few methods could have changed it

Tip: Start with everything private and only make something public when there is a clear reason. It is easy to open up a class later and very hard to close it once other code depends on its internals.

Test yourself

What is the main purpose of encapsulation?

  1. Making programs run faster
  2. Protecting an object's invariants by controlling access to its data
  3. Allowing multiple inheritance
  4. Reducing the number of classes

A class has a private balance_ and only deposit/withdraw methods. How can outside code set the balance to -5?

  1. acc.balance_ = -5
  2. It cannot, unless a method allows it
  3. Using a getter
  4. By inheriting from it

Why can encapsulated classes change their internal representation safely?

  1. Because the compiler rewrites the callers
  2. Because callers only depend on the public interface
  3. Because private members are never used
  4. They cannot