Data abstraction is a process of providing only the essential details to the outside world and hiding the internal details. i.e. representing only the essential details in a program.
Data abstraction is a programming technique that depends on the separation of the interface and implementation details of a program.
Let's take a real life example of an AC, which can be turned on or off, change the temperature, change the mode and other external components such as fan, swing. But we don't know the internal details of the AC. i.e. how it works internally. Thus we can say that AC separates the implementation details from the external interface.
C++ provides a great level of abstraction. For example, pow() function is used to calculate the power of a number without knowing the algorithm the function follows.
In C++ program, if we implement a class with private and public members, then it is an example of data abstraction.
Data abstraction can be achieved in two ways:
- Abstraction using classes.
- Abstraction in header files.
Abstraction Using Classes
An abstraction can be achieved using classes. A class is used to group all the data members and member functions into a single unit using the access specifier. A class has a responsibility to determine which data member is to be visible outside and which one is not.
Abstraction in Header file
Another type of abstraction is header file. For example, the pow() function available is used to calculate the power of a number without knowing which algorithm uses to calculate the power. Thus we can say that the header file hides all the implementation details from the user.
Access Specifiers
- Public Specifier: When the members are declared as public, members can be accessed anywhere from the program.
- Private specifier: When the members are declared as private, members can be accessed only by the member functions of the class.
Let us see a simple example of abstraction in header file
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int n = 4;
int power = 3;
int result = pow(n, power);
cout<<"Cube of n is: "<<result<<endl;
return 0;
}
When you compile the above program, you will get this result:
Comments (0)