Topic 52 of 83
Encapsulation
Overview
Encapsulation is the concept of bundling data and methods together and hiding the internal state of the object (`private` variables). This protects data from accidental corruption and makes code easier to refactor.
Syntax
cpp
class Thermostat {
private:
int temperature; // Hidden data
public:
void setTemp(int t) {
if (t >= 60 && t <= 90) { // Validation logic protects the state
temperature = t;
}
}
};Common Pitfalls
- Returning a non-const pointer or reference to a private variable, which breaks encapsulation by allowing outsiders to modify it directly.
Interview Tips
- Encapsulation != Abstraction. Encapsulation is about 'hiding internal state' (private variables). Abstraction is about 'hiding complexity' (exposing only simple methods).
Real-World Example
Protecting a Bank Account balance.
example
cpp
/*
If balance was public:
account.balance = -9999; // Total system collapse
With Encapsulation:
void withdraw(int amount) {
if (amount > 0 && balance >= amount) {
balance -= amount;
}
}
*/