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.
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
- All public paths that change data validate it.
- Accessor functions can compute values on demand.
- Representation stays private.
Code examples
An invariant protected
rejected: 0-100 only 40
Changing the representation safely
0.3
Storing paise internally avoids floating-point drift; users never see the representation.
More examples
A stack whose size always matches its contents
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:
Practical applications
std::vectorhides 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
Prefer
Comments don't enforce rules; private data does.
Getter returning a non-const reference to private data
Avoid
Prefer
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
- 1Write a
Clockclass with hours and minutes that can only be advanced throughtick(minutes). - 2Change 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?