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:Â
Â
See more on Object Oriented Programming.Â