3 encapsulation
3 encapsulation
Example
In a company, two software projects are going on with two different
teams. One team requires data from the other team. But this team
cannot access the data from the other team because they do not have
the appropriate permissions. This is Encapsulation.
Syntax for both is that they start with either get or set, followed by the
name of the variable, with the first letter in upper case:
Example --To access a private attribute, use public "get" and "set"
methods:
#include <iostream>
using namespace std;
class Employee {
private:
int salary; // Private attribute
The output of the above program is a compile time error because
wepublic:
are not allowed to access the private data members of a class
directly from outside the class.
// Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};
int main() {
Employee myObj;
myObj.setSalary(50000);
cout << myObj.getSalary();
return 0;
}
Example explained
Benefits of encapsulation: