Skip to content

Encapsulation

Encapsulation is the concept of bundling data (variables) and methods (functions) together inside a class, and restricting direct access to the internal details of an object.

Think of it like a medicine capsule — everything is packed inside, and you only interact with it from the outside without seeing what's within.

Two Key Ideas

  • Hiding data — mark fields as private so outsiders can't directly access them
  • Controlled access — expose only what's needed via public methods (getters/setters)

Example

cpp
class BankAccount {
    private double balance; // hidden from outside

    // controlled access
    public double getBalance() {
        return balance;
    }

    public void deposit(double amount) {
        if (amount > 0)
            balance += amount;
    }
};

Outside code cannot do account.balance = -5000. It must go through deposit(), which validates the input. That's encapsulation protecting your data.

Benefits

BenefitExplanation
Data protectionPrevents invalid or unauthorized changes
MaintainabilityInternal implementation can change without breaking outside code
ControlYou decide what to expose and what to hide

One-liner: "Encapsulation is wrapping data and methods into a class while restricting direct access to protect the object's integrity."