When all the data members and member functions are combined in a single unit called class, this process is called Encapsulation.This is to prevent the access to the data directly, the access to them is provided through the functions of the class. It also helps in 'data hiding'.
Data Hiding
Data hiding ensures exclusive data access to class members and protects object integrity by preventing unintended or intended changes.The goal of data hiding is to protect data within a class from unwanted access and to prevent unneeded intrusion from outside the class.
Features of Encapsulation
Encapsulation protects an object from unwanted access by clients.
It helps to control the modification of our data members.
Simplifies the maintenance of the application.
Q1.) Example of Encapsulation .
#include < iostream>
using namespace std;
class Rectangle {
public:
// Variables required for area calculation
int length;
int breadth;
// Constructor to initialize variables
Rectangle(int len, int brth) : length(len), breadth(brth) {}
// Function to calculate area
int getArea() {
return length * breadth;
}
};
int main() {
// Create object of Rectangle class
Rectangle rect(8, 6);
// Call getArea() function
cout << "Area = " << rect.getArea();
return 0;
}