C++ Encapsulation C-PLUS-PLUS

C++ Encapsulation  

C++ Encapsulation

C++ Encapsulation

Encapsulation is defined as wrapping up of data and information under a single unit. In Object-Oriented Programming, Encapsulation is defined as binding together the data and the functions that manipulate them.
Consider a real-life example of encapsulation, in a company, there are different sections like the finance section, accounts section, sales section, etc. The finance section handles all the financial transactions. Similarly, the sales section handles all the sales-related activities. Now there may arise a situation when for some reason an official from the finance section needs all the data about sales in a particular month. In this case, he is not allowed to directly access the data of the sales section. He will first have to contact some other officer in the sales section and then request him to give the particular data. This is what encapsulation is.

The meaning of Encapsulation is to make sure that "sensitive" data is hidden from users. To achieve this, you must declare class variables/attributes as private (cannot be accessed from outside the class). If you want others to read or modify the value of a private member, you can provide the public get and set methods.

 

Example

#include <iostream>
using namespace std;

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(30000);
  cout << myObj.getSalary();
  return 0;
}

Output:

30000

Advantages of Encapsulation

  • It is considered good practice to declare your class attributes as private (as often as you can). Encapsulation ensures better control of your data because you (or others) can change one part of the code without affecting other parts
  • Increased security of data

Download free E-book of C-PLUS-PLUS


#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries