Encapsulation is one of the important features of C++ (OOP) programming language.
Encapsulation in C++ is wrapping up of data and functions into single unit (class).
When we create a class and declare variables and functions inside it, we are basically binding them together with the help of class, thus implementing encapsulation.
With access specifier we can also hide data outside the class, which is called Data Hiding. Therefore we can say that encapsulation in a way implements abstraction.
C++ Example of Encapsulation in C++
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 |
#include <iostream> using namespace std; class Math{ private: int sum; //Can't be accessed in main (Data Hiding) public: Math(){} void add(int a, int b){ sum = a + b; } int getSum(){ return sum; } }; int main() { int result; //Single unit i.e object of a class Math math; math.add(5,4); cout << "Sum: "<< math.getSum() << endl; return 0; } |
In the above program variable sum is private , therefore it cannot be accessed from main. To access ‘sum’ we have created getSum() function which returns the value of ‘sum’. Also notice that by creating the class we have binded sum and getSum() to work together, which is only possible through object of the class (single unit).
Output
There is nothing much to learn in encapsulation in C++. Till now if you have not understood any of the parts then do comment below.