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:
1 2 3 4 5 6 7 8 9 10 11 12 13 | class Square { private: double side; public: 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++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | #include <iostream> using namespace std; class Rectangle { //private members private: float length; float breadth; public: // Setter for length and breadth void setLength(float l) { length = l; } void setBreadth(float b) { breadth = b; } // Getter for length and breadth float getLength() { return length; } float getBreadth() { return breadth; } // area function float getArea() { return length * breadth; } }; //main function int main() { Rectangle rect; //setting the length and breadth value rect.setLength(10); rect.setBreadth(6.5); // getting the length and breadth value float length = rect.getLength(); cout << "Length: " << length << endl; float breadth = rect.getBreadth(); cout << "Breadth: " << breadth << endl; // Area cout << "Area of a rectangle: " << rect.getArea(); return 0; } |
Output:
1 2 3 | Length: 10 Breadth: 6.5 Area of a rectangle: 65 |
In the above program length
and 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.