Trusted answers to developer questions

What is abstraction in programming?

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

Abstraction is used to hide background details or any unnecessary implementation about the data so that users only see the required information. It is one of the most important and essential features of object-oriented programming.

Pre-defined functions are similar to data abstraction.

For example, when you wash your laundry in a laundry machine, you put your laundry and detergent inside the machine and wait for the machine to perform its task. But how does the machine was your clothes? What mechanism does it use? A user is not required to know the engineering behind its workings. This process is similar data abstraction; it keeps all the unnecessary information hidden from the users.

Types of Abstraction

Abstraction using classes

Abstraction can be implemented with classes. Classes have private and public identifiers to limit the scope of any variable or a function.

Abstraction in header files

Header files of many languages store some pre-defined function, for example, the pow() function in C++, .sort(), etc. A user knows how and when to use them; however, their workings are kept hidden in these header files/libraries.

An example of Data Abstraction
An example of Data Abstraction

Users cannot access the private variables in the above illustration. However, they can be accessed and modified by the set() and get() methods. Let’s look at an example below:

Although members declared as public in a class can be accessed from anywhere in the program, members declared as private in a class can only be accessed from within the class.

Code

#include <iostream>
# include <string>
using namespace std;
class Abc
{
private:
// private name and id, use of abstraction
string name;
int id;
public:
// setter function
void set(string x, int y)
{
name = x;
id = y;
}
// getter function
string get_name()
{
return name;
}
int getId()
{
return id;
}
};
int main()
{
// declare an instance of class
Abc obj;
// set name and id
obj.set("Alex", 20);
// get name and id and output them
cout << obj.get_name() << " " << obj.getId() << endl;
return 0;
}

RELATED TAGS

c++ abstraction
abstraction
c++ abstraction
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?