C++ Encapsulation

C++Encapsulation: It is a process of wrapping of data and methods in a single unit. It is achieved in the C++ language by the class concept. The Combining state and behavior in a single container is known as encapsulation. In C++ language encapsulation can be achieved using a class keyword, the state represents a declaration of variables on attributes and behavior represents operations in terms of method.



C++Encapsulation

It supports the properties of encapsulation and data hiding through the creation of user-defined types, called classes. We can achieve encapsulation in two ways. They are as follows:

  • Create set and get functions as public for each data member in such a way that the set function sets the value for the data member and gets function get the value for the data member.
  • Making the entire data members private.

C++ encapsulation

C++ Encapsulation Advantages

  • The main advantage of using 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.
  • It provides abstraction between an object and its clients.
  • And protects an object from unwanted access by clients.
  • Example: A bank application forbids a client to change an Account’s balance.

Example:

#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

Output:
Enter any two number:
4
5
Sum: 9