Data Abstraction in C++

In this tutorial, we are going to learn about Data Abstraction in C++. Data Abstraction is the process of showing only the functionality of an object by hiding its implementation details. For example, we know that vehicles run using diesel or petrol. But, we don’t know how the engines of vehicle work using petrol or diesel. The given example shows Data Abstraction as the internal details are hidden from the user.

Below is our C++ code to perform the data abstraction task:

#include<bits/stdc++.h>
using namespace std;
int main(){
    vector<int> v = {3,2,1};
    //Function for sorting the elements
    sort(v.begin(),v.end());
    for(int i = 0; i < v.size();i++){
        cout<<v[i]<<' ';
    }
    cout<<endl;
}

The output result of the above code is given below:

1 2 3

In the above code, the sort() function sorts a given set of elements. But the algorithm which is used for sorting is hidden in the C++ Standard library. Similarly, we can make use of make use of many functions like reverse(), pow(), etc without knowing the algorithm behind them.

One of the salient features of object-oriented programming is Data Abstraction. Using the classes in C++ we can implement Data Abstraction easily. For example, we can hide the internal details of a class using private access specifier.

#include <bits/stdc++.h>
using namespace std;
class Circle{
    public:
        int radius;
        Circle(int d){
            radius = d;
        }
    private:
        float pi = 3.14;
    public:
        float area(){
            return pi*radius*radius;
        }
};
int main(){
    int x;
    cout<<"Enter the radius : ";
    cin>>x;
    Circle c(x);
    cout<<"The area of circle is "<<c.area()<<endl;
}

Output:

Enter the radius : 5
The area of circle is 78.5

In the above code, we used the private access specifier for hiding some of the internal details such as the value of pi. So these details are not visible and other classes cannot access them directly. But they will be helpful in showing the necessary functionality. By using Data Abstraction we can protect the internal details of a class from the errors in the user-level code. As the private members of a class cannot be accessed by the other classes, the internal implementation of a class can be changed without affecting the other classes. Data Abstraction also increases the code reusability. So we can say that Data Abstraction is one of the key features of programming.

We hope that you have got a clear idea of Data Abstraction in C++.

Leave a Reply

Your email address will not be published. Required fields are marked *