Abstraction & Encapsulation in C++

Abstraction

  • Data abstraction means hiding of data.
  • Abstraction is implemented automatically while writing the code in the form of class and object.
  • It shows only important things to the user and hides the internal details.

Example : Program demonstrating Data Abstraction

#include<iostream>
using namespace std;
class Addition
{
    private: int a=10,b=10,c;  // Hidden data from outside world
        public:
            int add()
            {
                 c=a+b;
                 cout<<"Addition is : "<<c;
            }
};
int main()
{
     Addition a;
     a.add();
     return 0;
}


Output:
Addition is : 20

  • In the above example, class Addition adds numbers together and returns the addition or sum. The public member add() function is the interface to the outside world and a user needs to know to use the class. The private member int a,b,c are something that the user does not need to know about, but is needed for the class to operate properly.
  • Abstraction provides security for the data from the unauthorized methods and can be achieved by using class.

Encapsulation

  • Encapsulation is a process of bundling the data and functions in a single unit.
  • It binds the data and functions together that manipulate the data and keeps them safe from outside interference and misuse.
  • It is used to secure the data from other methods. When making a data private, these data are used within the class only and not accessible outside the class.
Advantages of Encapsulation
  • Encapsulation provides abstraction between an object and its users.
  • It protects an object from unwanted access by unauthorized users.