Encapsulation in C++
C++ is based on object-oriented programming concepts. Encapsulation is one of the important features of Object Oriented Programming. Encapsulation is defined as the process of combining data members and functions in a single unit.
Features of Encapsulation
- In encapsulation, member variables of a class cannot be accessed from another class directly. Those member variables should only be accessible via functions.
- In encapsulation, the functions which we create must only use member variables.
- It increases the security of data.
Why Encapsulation?
- Encapsulation helps to keep the related data and functions together, which makes our code cleaner and easy to read.
- Encapsulation protects data from unauthorized access.
- Encapsulation helps to control the modification of class data members.
- Encapsulation helps to hide the data of class members from direct access by other classes by making the data private.
How to use Encapsulation in C++?
- First make all the data members of a class private.
- Then create public setter and getter functions for each data member in such a way that the set function sets the value of the data member and the get function gets the value of the data member.
Example
#include <iostream>
using namespace std;
class Employee
{
private:
// data hidden from outside world
double salary;
public:
// public function to set value
void setSalary(double fulltime, double overtime)
{
salary = fulltime + overtime;
}
// public function to return value
int getSalary()
{
return salary;
}
};
int main()
{
Employee employeeObj;
employeeObj.setSalary(4500, 510.55);
std::cout << "Employee salary is $";
cout << employeeObj.getSalary();
return 0;
}
Output
Employee salary is $5010.55