C++ | Abstraction

Updated: Jun 11

Abstraction means displaying only essential information and hiding the small print. Data abstraction refers to providing only essential information about the info to the surface world, hiding the background details or implementation.

Real life Example -

Man driving a car. The man only knows that pressing the accelerators will increase the speed of car or applying brakes will stop the car but he doesn't realize how on pressing accelerator the speed is really increasing, he doesn't realize the inner mechanism of the car or the implementation of accelerator, brakes etc within the car.

Data Abstraction can be achieved in two ways:

  1. Abstraction using classes

  2. Abstraction in header files.

Abstraction using classes:

An abstraction can be achieved using classes. A class is used to group all the data members and member functions into a single unit by using the access specifiers. A class has the responsibility to work out which data member is to be visible outside and which isn't.

Abstraction in header files:

An another type of abstraction is header file. For example, pow() function available is used to calculate the power of a number without actually knowing which algorithm function uses to calculate the power. Thus, we can say that header files hides all the implementation details from the user.

Access Specifiers Implement Abstraction:

  1. Public specifier: When the members are declared as public, members can be accessed anywhere from the program.

  2. Private specifier: When the members are declared as private, members can only be accessed only by the member functions of the class


#include <iostream> 
using namespace std; 

class implementAbstraction 
		int a, b; 

		// method to set values of 
		// private members 
		void set(int x, int y) 
			a = x; 
			b = y; 
		void display() 
			cout<<"a = " <<a << endl; 
			cout<<"b = " << b << endl; 

int main() 
	implementAbstraction obj; 
	obj.set(10, 20); 
	return 0; 


a = 10
b = 20

Advantages of Data Abstraction:

  • Data Abstraction avoids the code duplication, i.e., programmer does not have to undergo the same tasks every time to perform the similar operation.

  • The main aim of the data abstraction is to reuse the code and the proper partitioning of the code across the classes.

Happy Coding!

Follow us on Instagram @programmersdoor

Join us on Telegram @programmersdoor

Please write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem.

Follow Programmers Door for more.

#blog #interview #placement #learn #computer #science

        Contact Us


  • LinkedIn
  • Facebook
  • Instagram

©2023 by Programmers Door