Encapsulation

Encapsulation is wrapping up of class members under a single unit. In Object Oriented Programming, we say that encapsulation is the binding of data and functions that manipulates them. It is used to hide the sensitive data from users. If you want to access private data, you will use getter and setter functions.

Getter and Setter Functions:

These are public functions which are used to get and set the value of private data. They are not something special and implemented like simple functions. Getter or setter are not the keywords. These are just simple terms used for the functions. The function which sets the value of data members is called setter, and the function with the help of which we can access values in the main function is called getter function.

Encapsulation and real life example:

There is a library in a school. A librarian keeps the records of books. A student takes a book and does not return even after the issued due date. The librarian needs the data(can be private data) of student to contact him. He will contact the information section of school which will provide him data (getter function) to get data of the student. He does not has direct access to the data.

encapsulation.cpp
#include <iostream>
using namespace std;

class Employee{
  private:
    int salary;

  public:
    void setter(int salary) {
      this->salary = salary;
    }
    int getter() {
    	return salary;
    }
};

int main() {
  Employee emp1;
  emp1.setter(50000);
  cout << emp1.getter();
  
  return 0;
}

Note: This is encapsulation. We have declared the data member private and get it with the help of getter function. We are also setting its value with some function(Setting data with the help of some function is not the condition of encapsulation. We can also set the value in the class by simple expression, int salary = 20,000;)



Fully Encapsulated Class:

If a class has all its data members private, it is called fully encapsulated class.

Why Encapsulation:

  • You can hide your data.
  • Guarantees security.
  • If you want the class members unchanged, encapsulation will help you.