Encapsulation
in C++
Learn how to protect your data with private members and expose controlled access through public methods: the foundation of robust object-oriented design.
What Is Encapsulation?
Encapsulation is the practice of bundling data and the functions that operate on that data into a single unit (a class), while restricting direct access to the internal state. Only carefully chosen public methods can read or modify the hidden data.
Why Does It Matter?
The Capsule Model
The Three Access Specifiers
The Core Rule of Encapsulation
This creates a controlled gateway. Inside a setter, you can add validation (e.g., reject a negative bank balance). Inside a getter, you can add formatting or computation. The caller never knows how data is stored internally.
Getters and Setters
Getters return a copy of private data. Setters accept a new value, validate it, then update the private member. External code never touches the variable directly.
class vs struct
| class | struct | |
|---|---|---|
| Default access | private | public |
| Encapsulation | Encouraged by default | Must add private: manually |
| Convention | Objects with behavior | Simple data bundles (PODs) |
| Inheritance default | private | public |
How to Apply Encapsulation
private: specifier.Example 1: Student Class
Example 2: BankAccount
Example 3: TemperatureSensor
The Power of Validation
Common Mistakes
void setAge(int a){age=a;} without checking the input.Summary Checklist
| Principle | Do | Don't |
|---|---|---|
| Data members | private | public |
| Getters | Return by value or const ref | Return non-const reference |
| Setters | Validate before assigning | Blindly assign |
| Constructor | Set safe defaults | Leave members uninitialized |
| Keyword | Use class for encapsulated types | Use struct for complex objects |
Question 1 of 5
What is the default access specifier for members of a C++ class?
Question 2 of 5
Which of the following best describes encapsulation?
Question 3 of 5
Given the class below, what is the output?
Question 4 of 5
Why is returning a non-const reference from a getter considered a violation of encapsulation?
Question 5 of 5
A TemperatureSensor stores data internally in Celsius. A developer changes the internal storage to Kelvin but keeps the same public getters. What happens to code that calls getCelsius()?