PREV NEXT
What is abstraction?
- The data abstraction is one of the most essential and important feature of object oriented programming in C++. The data abstraction means displaying only essential information and hiding the details.
- It also refers to providing only essential details about the data to the outside world hiding the background details.
- In C++, the classes help us to group data members and member functions using available access specifiers. The classes decide which data member will be visible to the outside world and which is not.
- Let us look at the real life example of TV, which we use in daily life where you can turn off and on, change the channel, increase or decrease the volume but how it is working you do not know, the internal details you do not know it just receives the signals through a cable but how it translates and displays them on the screen you do not know.
- This is what abstraction is which hide the implementation details but shows the relevant information.
Access specifiers in abstraction
In C++, we use access specifiers to define the abstract interface to the class.
Private Label:
The members defined with private label are not accessible to code that uses the class. In the private section it hides the implementation from code that uses the type.
Public Label:
The members defined with a public label are accessible to all parts of the program. The abstraction view of a type is defined by its public members.
Advantages of Abstraction
The advantages of using data abstraction are:
- If you need to make any change in the high level code where private members are declared than you are not require to make any change in the low level code.
- It avoids the code duplication and increases the code reusability.
Let us have a look at the example to understand it better:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
#include <iostream> using namespace std; class Sum { public: // constructor Sum(int i = 0) { total = i; } // interface to outside world void add(int num) { total += num; } // interface to outside world int Total() { return total; }; private: // hidden data from outside world int total; }; int main() { Sum s; s.add(10); s.add(40); s.add(30); cout << "The total is:" << s.Total() <<endl; return 0; } |