Encapsulation is defined as the wrapping up of data(variable) under a single unit. Encapsulation is an important concept of OOP in C++ that binds data and functions inside a class together that manipulate them. Data encapsulation leads to the important concept called data hiding.
It makes sure that the ‘sensitive’ data are hidden from the user and an access specifier is used to achieve this.
private specifier is used to hide sensitive data, it makes the data inaccessible from outside the class. But to modify or read those data, we need to use the getter and setter (i.e. get and set) method. It prevents from accessing the data directly.
Example of specifiers to bind data:
void setSide(int s)
if (s >= 0)
side = s;
Let us go through an example in C++ to understand the concept of hiding data.
Data Hiding Using the private Specifier in C++
using namespace std;
// Setter for length and breadth
void setLength(float l)
length = l;
void setBreadth(float b)
breadth = b;
// Getter for length and breadth
// area function
return length * breadth;
//setting the length and breadth value
// getting the length and breadth value
float length = rect.getLength();
cout << "Length: " << length << endl;
float breadth = rect.getBreadth();
cout << "Breadth: " << breadth << endl;
cout << "Area of a rectangle: " << rect.getArea();
Area of a rectangle: 65
In the above program
breadth in Rectangle class is a private member which means they are not accessible from outside the class. So to get and set the value of length and breadth, we created a setter (pass the value) and getter (return the value). Hence the private members are not accessible directly, making it hidden.
Benefits of Encapsulation:
- Data- hiding in Java.
- The class field can be made read-only or write-only.
- It provides the class the total control over the data.
String Pattern Programs in C
Java Program to Find pair of Integers in Array whose sum is given Number
Program to Print Diamond Alphabet Patterns in C
Half Diamond Pattern in C using Alphabets
Half Pyramid of Alphabets in C