• Register
100 points
7 4

Encapsulation is a feature or concept of OOP (Object Oriented Programming), and we know OOP points to the real world things like inheritance, hiding, polymorphism in the programming world.

What is encapsulation in C++?

Encapsulation in C++ means binding of data with the functions that performs actions on that data. Encapsulation keeps us safe from outside interference and misuse. And that led us to the important concept of OOP which is data hiding. Encapsulation is used to hide the values or state of a structured data object inside a class, preventing the interference with them.

 

Data hiding

Data hiding is also a concept of Object Oriented Programming (OOP) that hides details of internal objects. 
The belief behind data hiding is to conceal data within a class, so it can be prevented or protected to be accessed by the outside class. Data hiding helps us to create classes with unique data sets and functions by avoiding unnecessary penetration from other program classes.
There is a slight difference between data hiding and data encapsulation, data hiding hides only class data elements, whereas data encapsulation hides class data parts and private functions/methods.
 

Example

We know that class has public, private and protected members. And private members hide data from the inherited class or child class. So, any program where we use a class with public and private members is an example of data encapsulation and also of data abstraction.

#include <iostream>
using namespace std;

class Adder {
   public:
      // constructor
      Adder(int i = 0) {
         total = i;
      }
      
      // interface to outside world
      void addNum(int number) {
         total += number;
      }
      
      // interface to outside world
      int getTotal() {
         return total;
      };
   
   private:
      // hidden data from outside world
      int total;
};

int main() {
   Adder a;
   
   a.addNum(10);
   a.addNum(20);
   a.addNum(30);

   cout << "Total " << a.getTotal() <<endl;
   return 0;
}

The public members addNum and getTotal are the interfaces to the outside world and a user needs to know them to use the class. The private member total is something that is hidden from the outside world.

100 points
7 4