Encapsulation is the concept of bundling the data (variables) and the methods (functions) that operate on the data into a single unit called a class. It also restricts access to some of the object’s components, making it possible to prevent unintended interference and misuse by controlling how the data is accessed or modified.
Data is hidden and can only be accessed or modified using special functions (like getter and setter).
Example:
#include <iostream>
using namespace std;
class Employee {
private:
string name; // private data member
public:
// Setter method to set the name
void setName(string n) {
name = n;
}
// Getter method to get the name
string getName() {
return name;
}
};
int main() {
Employee emp;
// Set the name using the setter method
emp.setName("John");
// Get the name using the getter method
cout << "Name: " << emp.getName() << endl;
return 0;
}
Explanation:
- name is a private variable, meaning it cannot be accessed directly outside the class.
- To modify or read name, we use public methods setName() and getName(). These methods control how the data is accessed or changed.
- This ensures that the internal state of the object (name) is protected and cannot be directly altered by code outside the class.
Output:
Benefits of Encapsulation
1. Improved security and control over data.
2. Code maintainability: Changes to the internal implementation of a class can be made without affecting external code that uses the class, as long as the interface (public methods) remains the same.
3. Prevents unauthorized access and modification of data.
4. Makes the code easier to understand and maintain by keeping implementation details hidden.