Abstraction is one of the features of C++ (OOP) programming language.

Abstraction basically means hiding background or implementation details and showing only essential or important information.

Example: Consider smartphone. We run various types of apps and games, click photos with the camera, make calls etc in our smartphone. Though we definitely know what a smartphone can do? but how it all gets done is hidden from us?

Similarly, abstraction in C++ hides certain details which we want them to get hidden from the outside world (user)?

So being a programmer it’s our responsibility to show only relevant information to our user.

How to implement abstraction in C++?

Abstraction in C++ is implemented in two ways:

Abstraction using Class

When we define class we also define its attributes (data members) and its behavior (member methods), due to which two case may arise:

  • If we call any of the class function using its object then we only get the result as the return value. We don’t get to know how the returned value has been calculated?
  • Similarly, when any of the data members is declared as private (access specifier)then it cannot be accessed outside of its class.

Thus the implementation details of the function remain hidden and as a result, implements abstraction.

Example:

Output

Output of abstraction program in C++

In the above program, the main function will not be able to get how the sum is being calculated and how many data members are there in the class because all are either hidden or private.

Abstraction using Header File

Header files also implements abstraction in a way. Take math.h as example. we include it to use math functions such as pow(), sqrt() etc. But we doesn’t get the details on how the result is being computed?

Example:

Output

C++ abstraction example

Note: We can also make our own header file and use it in other program file in order to implement abstraction.

Advantages of Abstraction in C++

  • Hides low level code implementation or details in the design level.
  • Allows to change the implementation details any time without letting the user to know.
  • Helps in code re-usability.
  • Increases the security of the program by showing only important details to the user.

That’s all for abstraction in C++. If you have any doubt then comment below.

Leave a Reply

Close Menu