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:ย 
ย 


Discover more from A Streak of Communication

Subscribe to get the latest posts sent to your email.

Discover more from A Streak of Communication

Subscribe now to keep reading and get access to the full archive.

Continue reading