C++ Encapsulation
Encapsulation is the idea of wrapping data and the code that works on that data together inside a single unit, the class, and then hiding the raw data behind a controlled interface. It is one of the core principles of object-oriented programming and it builds directly on the access specifiers you just learned.
Why encapsulation matters
When you make data members private and provide public methods to read or change them, you protect your object from being put into an invalid state. Other code cannot reach in and set a value to something nonsensical, because it must go through methods that you wrote and that you can add checks to.
- Better control: you decide exactly how a value can be read or modified.
- Safety: you can validate input before storing it.
- Flexibility: you can change how data is stored internally without breaking code that uses your class.
Private data with getter and setter methods
#include <iostream>
using namespace std;
class Employee {
private:
int salary; // hidden
public:
// Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};
int main() {
Employee emp;
emp.setSalary(50000);
cout << "Salary: " << emp.getSalary();
return 0;
}The pair of methods above is often called a getter (returns the value) and a setter (changes the value). Because salary is private, they are the only doorway to it, which means the class is fully in charge of that field.
Adding validation inside a setter
#include <iostream>
using namespace std;
class Thermostat {
private:
int temperature;
public:
void setTemperature(int t) {
if (t < 10) t = 10; // never below 10
if (t > 30) t = 30; // never above 30
temperature = t;
}
int getTemperature() {
return temperature;
}
};
int main() {
Thermostat room;
room.setTemperature(45); // too high, clamped
cout << room.getTemperature(); // prints 30
return 0;
}As a rule of thumb: keep your data private, expose behavior through public methods, and only add a getter or setter when you genuinely need outside access. Encapsulation is about giving your class a clean, dependable front door.
Exercise: C++ Encapsulation
What is the primary purpose of declaring class member variables as private in C++?