C++ Abstraction

Data abstraction is the property by which only the essential details are displayed to the user. The trivial or non-essential units are not displayed to the user.

It reduces the complexity of viewing things. It may be defined as the process of identifying only the required characteristics of an object hiding unnecessary or irrelevant details.

Abstraction Implementation

We can execute Abstraction in C++ using Class that helps to group data members and member functions using available access specifiers. A Class can choose which data member will be visible and which is not. 

Data Abstraction using Access Specifiers

Access specifier is the main pillar of implementing abstraction in C++. We can use access specifiers to enforce constraints on class members. 

Example:

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

Program for C++ Abstraction

#include <iostream> 
using namespace std;   
class implementAbstraction 

    private: 
        int a, b;   
    public:       
        // 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(1, 2); 
    obj.display(); 
    return 0; 

Output:

a = 1 b = 2

You can see in the above program we are not allowed to access the variables a and b directly, however, one can call the function set() to set the values in a and b and the function display() to display the values of a and b.

Advantages of Data Abstraction

  • Supports the user to avoid writing the low-level code
  • Evades code duplication and increases reusability.
  • Can change the internal implementation of class independently without affecting the user.
  • Improves the security of an application or program as only essential details are given to the user.

Leave a Comment

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