Abstraction in C++ with Examples

Abstraction is one of the salient concepts of Object-Oriented Programming. This topic is not a complex one, but still, many are not well versed with it. We at TechVidvan will help you to understand abstraction from the very basics.

What is Abstraction in C++?

Abstraction refers to the act of representing the crucial requisite features without including the additional explanations of such features. Hence, it means providing the end-user with their needs but without the details of how the needs were fulfilled.

For instance, we know how the switches at our houses work. Say for the fans, we just simply turn on the switch if we want to switch it on, or turn off the switch if we want to switch it off. In the case of fans, we can even use the regulator to adjust the speed according to our needs. Thus, we know all the features but we don’t know what the background implementation is. This is a real-life example of data abstraction.

Types of Abstraction in C++

There are 2 types of abstraction in C++:

1. Data Abstraction: It hides the information about the data.
2. Control Abstraction: It hides the information about the implementation.

Implementation of Abstraction in C++

The concept of data abstraction can be implemented in two different ways:

1. Using classes

The simplest way to achieve or implement abstraction is to use classes. A class can be used to group every data member and function into a solo unit with help of access specifiers. A class can determine which data of the class could be accessible to the outside world. In this way with the use of access specifiers, classes help to implement abstraction.

2. Through header files

Another type of abstraction in C++ is with header files. For example, if we put the header file for mathematical operations i.e. <cmath> or <math.h>, at the start of the program we can use the sqrt() function to find the square root of any given number. In this way, we know what sqrt() does, but we do not know the background details of how it finds the square root.

Let us take a simple program to find the square root of a number given by the user.

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
  double num, answer;
  cout<<"Enter a number: ";
  cin>>num;
  answer = sqrt(num);
  cout << "\n Square root of " << num << " is " << answer ;
}

Output:

Enter a number: 49

Square root of 49 is 7

…Program finished with exit code 0
Press ENTER to exit console.

So, we can see that we can simply use the sqrt() function from the <cmath> library to find the square root, but we don’t even know the background details.

Access specifiers in C++

Access specifiers are the main feature to hold the implementation data abstraction intact in C++. We can use them to determine which class members can be visible to the outside world and which can not be. Such restrictions can be put with the help of public, private, and protected keywords.

1. Data members prefixed with the public keyword are accessible throughout the program.

2. Data members prefixed with the private keyword are accessible only within the class where they are declared. Hence, they are restricted to that class and can not be accessed by the members outside the class.

3. Data members prefixed with the protected keyword are accessible to the members of the class. It is a special kind of access specifier and is similar to private access specifiers.

Let us consider a simple C++ program to find the sum of two integer values.

#include <iostream>
using namespace std;

class dataAbstraction {
public:
    int a, b;

public:
    void data()
    {
        cout << "Welcome to TechVidvan! \n";
        cout << "Enter Two values : "; 
        cin >> a >> b;
    }
public: 
    void display()
    {
        cout << "The sum is "<< a+b;
        cout << "\n";
    }
};
int main()
{
    dataAbstraction dA;
    dA.data();
    dA.display();
}

Output:

Welcome to TechVidvan!
Enter Two values : 4 9
The sum is 13

…Program finished with exit code 0
Press ENTER to exit console.

We can see that everything gets displayed properly. It is because of the fact that every data member was declared public. Since they were all declared public, they had access to each other.

Now let us see what happens if we declare the display function private.

#include <iostream>
using namespace std;

class dataAbstraction {
public:
    int a, b;

public:
    void data()
    {
        cout << "Welcome to TechVidvan! \n";
        cout << "Enter Two values : "; 
        cin >> a >> b;
    }
private: 
    void display()
    {
        cout << "The sum is "<< a+b;
        cout << "\n";
    }
};
int main()
{
    dataAbstraction dA;
    dA.data();
    dA.display();
}

If we run the above program code, the private data member will now be invisible to the other classes and hence it will throw an error on our screen.

Output:

Compilation failed due to following error(s).

main.cpp:26:16: error: ‘void dataAbstraction::display()’ is private within this context
    dA.display();
                ^
main.cpp:16:10: note: declared private here
    void display()
          ^~~~~~~

Benefits of Abstraction in C++

1. Abstraction increases the reusability of the code because of the proper partitioning.

2. It reduces the complexity as well as the redundancy of the code, hence increasing the readability.

3. Using classes and objects increases the security of the code. We can declare the parts of the code as private to keep them secure.

4. Due to abstraction, the important parts of the code are secure as only the essential features are provided to the user and they don’t know the background details.

5. Since the programmer can use the same code repeatedly, it helps us perform similar tasks for similar operations.

6. Abstraction allows changing internal implementations without affecting its user-level code.

7. Only the programmer can make changes to his data and methods, no one else.

8. The programmer need not write low-level code.

Design Strategy

Data Abstraction divided the code into two parts, interface and implementation. Hence, while writing the code we should maintain implementation as it is. That is, we should keep the interface independent of implementation. It even plays an important role in avoiding code duplication.

Hence, we can use the code again and again as it is and change the implementation, which even helps protect the data from the outside world.

Summary

In this tutorial, we learned about what data abstraction is and how we can implement it in two different ways. We even got to learn about the access specifiers used for data abstraction.

Besides the real-life example, we even went through some coding aspects of abstraction. Hopefully, this tutorial cleared the concept of data abstraction for you!

Keep learning at TechVidvan!