Encapsulation in C++

Encapsulation is binding the data and functions together into a single unit. The access of data is not provided directly. It is exposed through functions. 

There are 2 access specifiers called private and public. 

 

For example: 
#include <string>
using namespace std;


class Encap
{
string m_name; // Default specifier is private
public:


void SetName( string tempName)
{
m_name = tempName;
}
string GetName()
{
return m_name;
}
};
int main()
{
Encap demo;


demo.SetName("Apple");
string name = demo.GetName();
cout << "Name entered : " << name<<endl;
return 0;
}
The private access specifiers are accessed only through the functions. GetName will access the private variable called m_name. GetName is a public specifier. Any object of the class can call getname and access the name stored.
 
The output is as follows: