Encapsulation - EduardoMSU/OOP-2143 GitHub Wiki
Encapsulation is a fundamental principle of object-oriented programming (OOP) that involves bundling data (attributes) and methods (functions) that operate on the data into a single unit, i.e., a class. Encapsulation restricts direct access to an object’s internal state and enforces access control through defined interfaces.
Characteristic | Description |
---|---|
Data Hiding | Internal details of the class are hidden from the outside world using access modifiers. |
Controlled Access | Public methods provide controlled access to private attributes. |
Improved Security | Prevents unauthorized or accidental modification of data. |
Modularity | Promotes modular design by separating the implementation from the interface. |
Ease of Maintenance | Changes in the internal workings of a class don’t affect code that interacts with it externally. |
Encapsulation is enforced in C++ using access modifiers:
Access Modifier | Description |
---|---|
private |
Members are accessible only within the same class. |
protected |
Members are accessible within the same class and derived classes. |
public |
Members are accessible from outside the class. |
Below is an example demonstrating encapsulation in C++:
#include <iostream>
#include <string>
class Employee {
private:
std::string name; // Private attribute
int age; // Private attribute
public:
// Constructor
Employee(const std::string& empName, int empAge) : name(empName), age(empAge) {}
// Getter for name
std::string getName() const {
return name;
}
// Setter for name
void setName(const std::string& newName) {
name = newName;
}
// Getter for age
int getAge() const {
return age;
}
// Setter for age
void setAge(int newAge) {
if (newAge > 0) { // Validation
age = newAge;
} else {
std::cout << "Age must be positive!" << std::endl;
}
}
// Method to display employee details
void displayDetails() const {
std::cout << "Name: " << name << ", Age: " << age << std::endl;
}
};
int main() {
Employee emp("Alice", 25);
// Access and modify private members using public methods
emp.displayDetails();
emp.setName("Bob");
emp.setAge(30);
emp.displayDetails();
// Attempt to set invalid age
emp.setAge(-5);
return 0;
}