×
>
<

Aptitude

Encapsulation in C++

Encapsulation in C++

With C++ we achieve the functionality to wrap data and functions inside as a single form and keep them safe from outside world and achieve data hiding from and make the code more secure from unauthorised access.

Example

  • Payroll department would have all the information related to employee salaries, payments etc
  • The HR would have details of the employees, appraisals and performance information.
  • Similarly, Finance department would have all the information about the finances of the company.

  • For this they would need information from Payroll department and can’t access the information directly.
  • So they would send a request to HR department for the details.

  
#include<iostream>
using namespace std;

class myClass
{
  private:
    // This data hidden from outside world
    int salary;

  public:
    // function to set salary value 
    void setSalary(int s)
    {
      salary = s;
    }

    // function to return value of
    // variable x
    int getSalary()
    {
      return salary;
    }
};

// main function
int main()
{
  myClass myObj;
  myObj.setSalary(80000);

  cout << "The salary is: " << myObj.getSalary();
  return 0;
}
  

Observations –

  1. salary is made private and is not accessible by the outside world.
  2. salary details can only be manipulated, by getSalary and setSalary functions thus access is only restricted with predefined methods and there is no other way to manipulate them, these methods are binding data together.
  3. We have wrapped setting salary value in one code using function and getting salary using another function thus, achieving encapsulation that is wrapping and binding related data together and separating them with one another

To implement this –

  1. Data should always be in private mode
  2. The helper functions should be declared public using public access modifications.