Encapsulation in C++
Encapsulation is a process of wrapping of data and methods in a single unit. It is achieved in C++ language by class concept.
Combining of state and behavior in a single container is known as encapsulation. In C++ language encapsulation can be achieve using class keyword, state represents declaration of variables on attributes and behavior represents operations in terms of method.
Advantage of Encapsulation
The main advantage of using of encapsulation is to secure the data from other methods, when we make a data private then these data only use within the class, but these data not accessible outside the class.
Real Life Example of Encapsulation in C++
The common example of encapsulation is Capsule. In capsule all medicine are encapsulated in side capsule.
Benefits of encapsulation
- Provides abstraction between an object and its clients.
- Protects an object from unwanted access by clients.
- Example: A bank application forbids a client to change an Account's balance.
Example of Encapsulation in C++
#include<iostream.h> #include<conio.h> class sum { private: int a,b,c; public: void add() { clrscr(); cout<<"Enter any two numbers: "; cin>>a>>b; c=a+b; cout<<"Sum: "<<c; } }; void main() { sum s; s.add(); getch(); }
Output
Enter any two number: 4 5 Sum: 9
In above example all data and function are bind inside class sum.