C++ Abstraction

C++ Abstraction: Abstraction shows important things to the user and hides internal details. And hiding of data is known as “data abstraction“. Data abstraction can be used to provide security for data from unauthorized methods. While it also refers to providing only essential details about the data to the outside world hiding the background details.

C++ Abstraction

In C++, the classes help us to group data members and member functions using available access specifiers. The classes decide which data member will be visible to the outside world and which is not.

Access Specifiers in Abstraction:

In C++, we use access specifiers to define the abstract interface to the class.

  • Private Access Specifier
  • Public Access Specifier

Private Access Specifier

The members defined with private labels are not accessible to code that uses the class. In the private section, it hides the implementation from code that uses the type.

Public Access Specifier

The members defined with a public label are accessible to all parts of the program. The abstraction view of a type is defined by its public members.

Advantages of Abstraction

  • If you need to make any change in the high-level code where private members are declared then you are not required to make any change in the low-level code.
  • It avoids code duplication and increases the code re-usability.

Example:

#include<iostream.h>
#include<conio.h>
class sum
{
//hidden data from outside world
private: int a,b,c;
public:
void add()
{
clrscr();
cout<<"Enter any two numbers: ";
cin>>a>>b;
c=a+b;
cout<<"Sum: "<<c;
}
};
void main()
{
sum s;
s.add();
getch();
}

Output:

Enter any two number:
4
5
Sum: 9