The meaning of Encapsulation is to make sure that "sensitive" data is hidden from users.
It is one of the core principles of Object-Oriented Programming. To achieve encapsulation, you must:
private (so they cannot be accessed directly from outside).public get and set methods to view and modify the values of the private variables safely.Since private variables cannot be accessed directly, we use public methods (commonly referred to as "getters" and "setters") to interact with them.
#include <iostream> using namespace std;class Employee { private: // Private attribute int salary;
public: // Setter method void setSalary(int s) { // We can add logic here! (e.g., ensure salary is not negative) if (s > 0) { salary = s; } } // Getter method int getSalary() { return salary; } };
int main() { Employee emp;
// emp.salary = 50000; // This would cause an error!
emp.setSalary(50000); // Use setter to set the salary cout << "Employee Salary: $" << emp.getSalary() << "\n"; // Use getter return 0; }
You might wonder, why write extra code for getters and setters instead of just making variables public?
Here are the main benefits of Encapsulation:
setSalary method above, we can check if (s > 0) to ensure no one sets a negative salary. What is the primary way to achieve Encapsulation in C++?