Encapsulation in C++

Definition of Encapsulation:

  • Encapsulation is a key concept in Object Oriented Programming paradigm which combines the data(properties) and functions, related to the same object, together in a single unit.

Features

  • Data hiding is one of the important features of encapsulation.
  • We can make our data secure by making them read-only or write-only fields.
  • Properties and Functions of the related object are combined together.

Example:

Let’s take the example of XYZ Company. A company has many employees. Each and every employee has a name, different employee id, salary, etc. Suppose if you want to see the salary of an employee, for that you have to create a function or you want to know the name of the employee of a particular employee id, for that also you have to create a function.

The name of the employee or his/her salary details are confidential things and you want to keep them secure. Someone cannot change the details of the employee. This is Data Hiding.

Code:

Suppose you want to set the name and salary of an employee by passing id, name, and salary using encapsulation.

C++ Code

#include <iostream>

using namespace std;

class Company {
  private:
    string name;
  int salary;

  public:
    void setSalaryName(int ID, string name, int salary) {
      this -> name = name;
      this -> salary = salary;
    }
  string getName() {
    return this -> name;
  }
  int getSalary() {
    return this -> salary;
  }
};

int main() {
  Company obj;
  obj.setSalaryName(1, "Striver", 100000);
  cout << "Name: ";
  cout << obj.getName() << "\n";
  cout << "Salary: ";
  cout << obj.getSalary();
  return 0;
}

Output:

Name: Striver

Salary: 100000

Special thanks to Ankit Kumar Mishra for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article