Skip to content

Module 5 · Classes and Objects — topic 4 of 5

Encapsulation

Hide data behind a public interface so objects can never be put into an invalid state. Learn access specifiers, invariants, getters/setters done right, and friend.

Beginner 12 min read·Lesson 20 of 40 in C++ Programming

Learning objectives

  • Use private, protected and public deliberately
  • Identify and protect class invariants
  • Design behaviour-rich interfaces instead of raw setters

Definition

Encapsulation is the bundling of data with the operations on it and the restriction of direct access to that data, so that a class can maintain its invariants and change its implementation without affecting its users.

Introduction

A Temperature in Kelvin must never be negative; a Stack size must match its contents. If data members are public, any code can break these rules. Encapsulation lets the class guarantee them.

Why it matters

Encapsulation is one of the four OOP pillars examined in every OOP course.

It allows changing internal representation (e.g. storing Celsius instead of Kelvin) without changing user code.

Detailed explanation

public members are accessible everywhere, private only inside the class (and friends), protected inside the class and its derived classes.

An invariant is a condition that holds for every valid object. Constructors establish invariants; every public member function preserves them.

Prefer operations that express intent (withdraw(amount)) to setters that expose fields (setBalance(x)), which merely move the validation problem elsewhere.

A friend function or class can access private members; use it sparingly for tightly coupled helpers such as operator<<.

Syntax

C++
class Temperature {
public:
explicit Temperature(double kelvin) { set_kelvin(kelvin); }
double kelvin() const { return k_; }
double celsius() const { return k_ - 273.15; }
void set_kelvin(double k) {
if (k < 0) throw std::invalid_argument("below absolute zero");
k_ = k;
}
private:
double k_ = 0;
};
  • All public paths that change data validate it.
  • Accessor functions can compute values on demand.
  • Representation stays private.

Code examples

An invariant protected

C++
#include <iostream>
#include <stdexcept>
class Percentage {
public:
explicit Percentage(int v) { set(v); }
void set(int v) {
if (v < 0 || v > 100) throw std::out_of_range("0-100 only");
value_ = v;
}
int get() const { return value_; }
private:
int value_ = 0;
};
int main() {
Percentage p(40);
try { p.set(120); } catch (const std::out_of_range& e) { std::cout << "rejected: " << e.what() << '\n'; }
std::cout << p.get() << '\n';
return 0;
}
Output
rejected: 0-100 only
40

Changing the representation safely

C++
#include <iostream>
class Money {
public:
static Money rupees(double r) { return Money(static_cast<long long>(r * 100 + 0.5)); }
double as_rupees() const { return paise_ / 100.0; }
Money plus(Money o) const { return Money(paise_ + o.paise_); }
private:
explicit Money(long long p) : paise_(p) {}
long long paise_;
};
int main() {
Money a = Money::rupees(0.1), b = Money::rupees(0.2);
std::cout << a.plus(b).as_rupees() << '\n';
return 0;
}
Output
0.3

Storing paise internally avoids floating-point drift; users never see the representation.

More examples

A stack whose size always matches its contents

C++
#include <iostream>
#include <stdexcept>
#include <vector>
class BoundedStack {
public:
explicit BoundedStack(std::size_t capacity) : capacity_(capacity) {}
void push(int v) {
if (items_.size() == capacity_) throw std::overflow_error("stack full");
items_.push_back(v);
}
int pop() {
if (items_.empty()) throw std::underflow_error("stack empty");
int v = items_.back();
items_.pop_back();
return v;
}
std::size_t size() const { return items_.size(); }
friend std::ostream& operator<<(std::ostream& os, const BoundedStack& s) {
os << '[';
for (std::size_t i = 0; i < s.items_.size(); ++i) os << (i ? "," : "") << s.items_[i];
return os << ']';
}
private:
std::size_t capacity_;
std::vector<int> items_;
};
int main() {
BoundedStack s(2);
s.push(1);
s.push(2);
try { s.push(3); } catch (const std::overflow_error& e) { std::cout << e.what() << '\n'; }
std::cout << s << " size " << s.size() << '\n';
std::cout << s.pop() << ' ' << s << '\n';
return 0;
}
Output
stack full
[1,2] size 2
2 [1]

Step-by-step explanation

  • The capacity and contents are private; only push/pop change them.
  • push refuses to exceed capacity; pop refuses when empty.
  • operator<< is a friend so it can print the private vector.
  • No outside code can make size disagree with the contents.

Expected output

Running “A stack whose size always matches its contents” prints exactly:

TextOutput
stack full
[1,2] size 2
2 [1]

Practical applications

  • std::vector hides its pointer, size and capacity behind member functions.
  • Domain classes (Order, Invoice) protect business rules.
  • APIs keep internals private so libraries can evolve without breaking users.

Best practices

  • Make data members private by default.
  • Expose operations, not fields.
  • Return const references or copies from accessors.

Common mistakes

Public data with a comment saying 'don't change'

Avoid

struct Account { double balance; /* never negative! */ };

Prefer

class Account { double balance_ = 0; public: bool withdraw(double a); };

Comments don't enforce rules; private data does.

Getter returning a non-const reference to private data

Avoid

std::vector<int>& items() { return items_; }

Prefer

const std::vector<int>& items() const { return items_; }

Returning a mutable reference lets callers bypass every check.

Important notes

  • Access control is enforced at compile time; it is not a security boundary against malicious code in the same process.
  • Encapsulation applies to modules too: keep helpers in an unnamed namespace in the .cpp file.

Key takeaways

  • Encapsulation = data + operations, with restricted access.
  • Constructors establish and member functions preserve invariants.
  • Prefer behaviour-rich interfaces to raw setters.

Try it yourself

  1. 1
    Write a Clock class with hours and minutes that can only be advanced through tick(minutes).
  2. 2
    Change BoundedStack to use a fixed array internally without changing main.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

4 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is the main purpose of encapsulation?
  • ModerateWhich accessor breaks encapsulation of a private `std::vector<int> items_`?
  • ModerateWhat is a class invariant?
Practise this topic