DEFINITION 7: ENCAPSULATION - PRATMG/2143-OOP-Tamang GitHub Wiki
Encapsulation is defined as the grouping of data and information into a single unit known as a class. Encapsulation, in other words, is the act of combining which data members and methods or functions inside a class that alter the data, and keeping both safe from outside interference and misuse. As a result, the data is hidden from being accessible directly from outside the class.
Encapsulation is an important object-oriented programming technique that hides facts about an object from its users. It's referred to as "data hiding." Encapsulation is achieved by making all data members private and generating public setter and getter functions for each data member, with the set function setting the value of the data member and the get function retrieving the value of the data member.
There are three different encapsulations:
- Member Variable Encapsulation
- Function Encapsulation
- Class Encapsulation
// c++ program to explain
// Encapsulation
#include<iostream>
using namespace std;
class Encapsulation
{
private:
// data hidden from outside world
int x;
public:
// function to set value of
// variable x
void set(int a)
{
x =a;
}
// function to return value of
// variable x
int get()
{
return x;
}
};
// main function
int main()
{
Encapsulation obj;
obj.set(5);
cout<<obj.get();
return 0;
}
REFERENCE: