Encapsulation is a core principle of object-oriented programming in C++. It refers to bundling the data (attributes) and methods (functions) that operate on the data into a single unit, or class. Encapsulation also restricts direct access to some components, which is crucial for protecting the internal state of an object.
#include <iostream>
#include <string>
class Employee {
private:
std::string name;
int id;
double salary;
public:
// Constructor
Employee(const std::string& n, int i, double s) : name(n), id(i), salary(s) {}
// Getter for name
std::string getName() const {
return name;
}
// Getter for ID
int getId() const {
return id;
}
// Getter for salary
double getSalary() const {
return salary;
}
// Setter for salary
void setSalary(double s) {
if (s >= 0) {
salary = s;
}
}
// Method to display employee information
void display() const {
std::cout << "Name: " << name << ", ID: " << id << ", Salary: " << salary << std::endl;
}
};
int main() {
Employee emp("John Doe", 12345, 50000.0);
emp.display();
// Modifying salary using setter
emp.setSalary(55000.0);
std::cout << "Updated salary: " << emp.getSalary() << std::endl;
return 0;
}
name
, id
, and salary
are private and cannot be accessed directly from outside the class.getName()
, getId()
, getSalary()
, and setSalary(double)
are public, allowing controlled access to private data.salary
is restricted, and it can only be modified through setSalary()
, ensuring salary cannot be set to a negative value.private
, public
, and protected
to enforce encapsulation.