Abstraction in C++ with example
Abstraction is one of the features of Object-Oriented Programming, where you show only relevant details to the user and hide irrelevant details. For example, when you send an email to someone you just click send and you get the success message, what actually happens when you click send, how data is transmitted over the network to the recipient is hidden from you (because it is irrelevant to you).
Let’s see how this can be achieved in a C++ program using access specifiers:
Abstraction Example
#include <iostream> using namespace std; class AbstractionExample{ private: /* By making these data members private, I have * hidden them from outside world. * These data members are not accessible outside * the class. The only way to set and get their * values is through the public functions. */ int num; char ch; public: void setMyValues(int n, char c) { num = n; ch = c; } void getMyValues() { cout<<"Numbers is: "<<num<< endl; cout<<"Char is: "<<ch<<endl; } }; int main(){ AbstractionExample obj; obj.setMyValues(100, 'X'); obj.getMyValues(); return 0; }
Output:
Numbers is: 100 Char is: X
Advantage of data abstraction
The major advantage of using this feature is that when the code evolves and you need to make some adjustments in the code then you only need to modify the high level class where you have declared the members as private. Since none class is accessing these data members directly, you do not need to change the low level(user level) class code.
Imagine if you had made these data members public, if at some point you want to change the code, you would have to make the necessary adjustments to all the classes that are accessing the members directly.
1) Makes the application secure by making data private and avoiding the user-level error that may corrupt the data.
2) This avoids code duplication and increases code reusability.
Related Posts:
- Data Types in C++
- Operators in C++
- Recursion in C++ with example
- Functions in C++ with example
- goto statement in C++ with example
- Break statement in C++ with example
- Continue Statement in C++ with example
- do-while loop in C++ with example
- While loop in C++ with example
- For loop in C++ with example
- Switch Case statement in C++ with example
- If else Statement in C++
- Constructors in C++
- Enumeration in C++
- OOPs Concepts in C++
- this pointer in C++
- Pointers in C++
- Strings in C++
- Passing Array to Function in C++
- Multidimensional Arrays in C++
- Arrays in C++
- Difference between Function Overloading and Function overriding in C++
- Function Overriding in C++ with examples
- Function overloading in C++ with examples
- Polymorphism in C++ and its types
- Inheritance in C++ with examples
- Destructors in C++ with examples
- Encapsulation in C++ with example
- Friend Class and Friend Functions in C++
- Interfaces in C++ with Examples