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.
Abstraction can be implemented with classes. Classes have private and public identifiers to limit the scope of any variable or a function.
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.
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.
#include <iostream># include <string>using namespace std;class Abc{private:// private name and id, use of abstractionstring name;int id;public:// setter functionvoid set(string x, int y){name = x;id = y;}// getter functionstring get_name(){return name;}int getId(){return id;}};int main(){// declare an instance of classAbc obj;// set name and idobj.set("Alex", 20);// get name and id and output themcout << obj.get_name() << " " << obj.getId() << endl;return 0;}