38-Encapsulation in C++-04-09-2023
38-Encapsulation in C++-04-09-2023
Encapsulation in C++:
Access specifiers:
Member functions are functions that are defined inside a class and
operate on the data members of that class. Because they are a component
of the class, member functions can access the private members of the
class. Member functions can be classified into two types: accessor
functions and mutator functions.
Mutator functions are member functions that modify the state of the
object by changing the value of the data members. Mutator functions
have access to and control over a class's private members. Examples of
mutator functions include set() and update() functions.
Data hiding:
In this example, we have defined a class named Employee that has three
private data members: empId, empName, and empSalary.
We have also defined six public member functions: setEmpId(),
setEmpName(), setEmpSalary(), getEmpId(), getEmpName(), and
getEmpSalary().
The values of the private data members are set using the set functions,
which are mutator functions. The values of the private data members are
retrieved using the get functions, which are accessor functions.
class Employee {
private:
// Private attribute
int salary;
public:
// Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};
int main() {
Employee myObj;
myObj.setSalary(50000);
cout << myObj.getSalary();
return 0;
}