Now, there are two types of Abstraction –
Header Files – We all know that using #include , lets us use pow() function, using the pow() function and passing the arguments we can calculate the power of any number. But, the implementation details are hidden from us, we just get the desired output without knowing what happened in the background.
Classes – With the help of Abstraction in C++ we can define which class members i.e. data members and member functions’s implementation we want to show to the outside world and which one’s we want to hide, using access specifiers.
Difference between Data Abstraction and Data Encapsulation
90% of the people forget both data abstraction and encapsulation in the interviews as both of them are more or less same. But, infact they are different.
- Data Encapsulation is the process of hiding the data and programs from the outside world and essentially capsuling them together in one entity.
- Data Abstraction is the process of hiding the implementation i.e. what is happening inside a function or program from the outside world. Essentially data abstraction is achieved with the help of data encapsulation or we can say abstraction is the result of encapsulation.
- Private members can only be access within the class and their data and implementation is hidden from the outside world
- Public members can be accessed anywhere in the program.
Example program for Data Abstraction
#include
using namespace std;
class myAbstractionClass
{
private:
int x ,y;
public:
// method to set values of
// private members
void setValue(int data1, int data2)
{
x = data1;
y = data2;
}
void displayValue()
{
cout<<"Value of x = " << x << endl;
cout<< "Value of y = " << y << endl;
}
int sum()
{
return x + y;
}
};
int main()
{
myAbstractionClass myObj;
// we can't use myObj.data1 directly, it is hidden and not allowed
myObj.setValue(100, 200);
myObj.displayValue();
// Here the user doesn't know how sum is implemented he just gets the result
// its same as for car we don't know how engine works, we just get interface to drive
cout << "The sum value is: " << myObj.sum()<< endl;
return 0;
}
Value of x = 100
Value of y = 200
The sum value is: 300
Now, we have achieved data abstraction in the above program in two ways –
- We can’t access the private members like x and y directly
- We are only able to set and print values with a function.
- We are only able to get the result of the sum value, but we don’t know how it may b working in the backend to calculate the sum