OOP: ENCAPSULATION
Achieving Encapsulation in C++
In C++, encapsulation is mainly achieved with:
privatedata- public methods
- validation
- clear class invariants
Step-by-Step Method
Step 1: Identify object state
For an Employee:
name
salary
Step 2: Make state private
private:
std::string name;
int salary;
Step 3: Expose safe public behavior
public:
bool setSalary(int amount);
int getSalary() const;
Step 4: Validate changes
bool setSalary(int amount) {
if (amount < 0) {
return false;
}
salary = amount;
return true;
}
Complete Example
#include <iostream>
#include <string>
class Employee {
private:
std::string name;
int salary = 0;
public:
explicit Employee(const std::string& employeeName)
: name(employeeName) {}
const std::string& getName() const {
return name;
}
int getSalary() const {
return salary;
}
bool setSalary(int amount) {
if (amount < 0) {
return false;
}
salary = amount;
return true;
}
};
int main() {
Employee employee("Mina");
if (!employee.setSalary(-200)) {
std::cout << "Invalid salary rejected\n";
}
employee.setSalary(50000);
std::cout << employee.getName() << ": $" << employee.getSalary() << '\n';
}
Access Specifiers and Encapsulation
| Access | Encapsulation role |
|---|---|
private |
hides state and helper details |
public |
exposes safe interface |
protected |
allows derived-class access, used carefully |
Interface Design Rule
Public methods should describe meaningful actions.
Good:
account.deposit(500);
account.withdraw(200);
Risky:
account.setBalance(300);
setBalance() may allow outside code to skip business rules.
Viva Answer
In C++, encapsulation is achieved by making data members private and exposing safe public methods that validate access and preserve object invariants. The public interface should contain meaningful operations, not just unrestricted setters.
Quick Check
- What are the steps to achieve encapsulation?
- What should be private?
- What should be public?
- Why can
setBalance()be worse thandeposit()andwithdraw()?