Encapsulation In C++

A Complete Overview of Encapsulation in C++:

We discussed Abstraction in detail in our previous tutorial. Abstraction, as we know, hides the implementation details from the user and exposes only the interface that is required by the user.

In this tutorial, we will discuss yet another important feature of OOP i.e. Encapsulation. Abstraction and encapsulation go hand in hand. In fact, we can say the encapsulated code helps us in abstraction. In other words, encapsulation and abstraction are closely bound together.

=> Visit Here For The Complete C++ Course From Experts.

Encapsulation

Thus, we can discuss these two concepts together as there is a very thin line between encapsulation and abstraction.

What Is Encapsulation?

Data encapsulation refers to the process of binding together data and functions or methods operating on this data into a single unit so that it is protected from outside interference and misuse.

This is an important object-oriented programming concept and it leads to yet another OOP concept known as “Data hiding”. Encapsulation hides data and its members whereas abstraction expose only the necessary details or interfaces to the outside world.

In a way, abstraction presents the “abstract view” of the hidden data to the outside world. Thus we already made a statement that encapsulation and abstraction go hand in hand.

encapsulation

A class in C++ is the one where we bundle together data members and the functions operating on these data members along with access specifiers like private, public and protected represent encapsulation. We have already discussed access specifiers in our earlier tutorial on classes and objects.

We also know that by default class members are private. When we declare class members as private and methods to access class members as public we are truly implementing encapsulation. At the same time, we provide an abstract view of data to the outside world in the form of public methods.

Implementation Of Encapsulation

Encapsulation in C++ is implemented as a class that bundles data and the functions operating on this data together. Mostly data is declared as private so that it is not accessible outside the class. The methods or functions are declared as public and can be accessed using the object of the class.

However, we cannot directly access private members and this is called data hiding. When this is done, data is secured and can be accessed only by functions of that particular class in which the data is declared.

// Example program
#include <iostream>
#include <string>
using namespace std;
//example class to demonstrate encapsulation
class sampleData{
   int num;
   char ch;
  
   public:
   //getter methods to read data values
   int getInt() const{
      return num;
   }
 
   char getCh() const{
      return ch;
   }
  
   //setter methods to set data values
   void setInt(int num) {
      this->num = num;
   }
 
   void setCh(char ch){
      this->ch = ch;
   }
};
int main()
{
   sampleData s;
   s.setInt(100);
   s.setCh('Z');
   cout<<"num = "<<s.getInt()<<endl;
   cout<<"ch = "<<s.getCh();
 
   return 0;
}

Output:

num = 100
ch = Z

encapsulation output

In the program above we have bundled two member variables along with the getter and setter methods into a class. and this is an example of encapsulation.

We have declared two variables i.e. num and ch as private variables so that they are not accessible to the outside world. They are only accessible to the functions that we have declared as public.  Thus we have hidden data members as private variables in a class.

Let us take another example to better understand Encapsulation in C++.

#include <iostream>
#include <string>
using namespace std;
//Accounts class: includes salary info for a particular employee
class Accounts{
 
   int empId;
 
   double salary, basic, allowances, deductions;
 
   public:
   Accounts(int empId):empId(empId){}
 
   //read salary info
   void readEmployeeInfo(int empId){
      cout<<"Enter basic for the employee"<<empId<<":"; cin>>basic;
      cout<<"allowances:"; cin>>allowances;
      cout<<"deductions:"; cin>>deductions;
 
   }
   //calculate salary
   double calculateSalary(){
      salary = basic+ allowances - deductions;
      return salary;
   }
 
   //display details
   void display(){
   salary = calculateSalary();
   cout<<"Employee: "<<empId<<endl;
   cout<<"Salary: "<<salary;
   }
 
};
int main()
   {
 
   Accounts acc(1);
   acc.readEmployeeInfo(1);
   acc.display();
}

Output:

Enter basic for the employee1:10000
allowances:4324.43
deductions:1000
Employee: 1
Salary: 13324.4

Encapsulation_example

This is yet another example of encapsulation. As shown above, we have a class Accounts that bundles account data and all the functions that operate on this data into a single class Accounts. In the main function, we can create an object of this class and access functions to get the desired information.

Now if some other classes say the employee details want to access accounts data, then it cannot do it directly. It will need to create an object of class Accounts and will be able to access only those items that are public. This way, using encapsulation we guarantee the access control of the data and also ensure the integrity of data.

Difference Between Encapsulation And Abstraction

Abstraction and encapsulation are closely bound together. Encapsulation aids in abstraction by bundling data and methods operating on that data together.

EncapsulationAbstraction
Hides the dataHides implementation
Bundles data and methods togetherProvides an abstract interface to the user exposing only what is required
Aids in abstractionAids in reuse and security of the code.
Implemented as a class with access specifiers defining access to data members and methodsImplemented as an abstract class and interfaces that cannot be instantiated.

Conclusion

Encapsulation is one of the most important features of OOP as it provides us a way to hide the data. This, in turn, makes data more secure and protects it from malicious use.

Encapsulation aids in abstraction, so that we can expose only the required interface to the end-user and hide other details accordingly. In this tutorial, we had a look at abstraction and encapsulation concepts in C++.

In our upcoming tutorial, we will discuss Inheritance in C++ with examples.

=> Visit Here For The Exclusive C++ Training Tutorial Series.