Encapsulation is used to hide or protect sensitive data or information from all users. In order to encapsulate the data, we must declare variables/attributes of a class as private so that they can’t be accessed from outside the class. Now, if we want to read or change the values of private members outside the class, we’ll have to use the public get
and set
methods.
The get
method is used to return the data/value. It is also known as an accessor method.
The set
method is used to set or update the value/data. It is also known as a mutator method.
Following are the benefits of using getters and setters.
Code readability: The code is very easy to read and understand. It is also easy to look for errors in the code.
Data protection: The data is protected as we cannot directly access the private members/attributes of a class.
Following is the basic C++ code to demonstrate the use of getters and setters:
#include <iostream>using namespace std;class Student{private:// Private attributeint rollNo;public:// Settervoid setRollNo(int id){rollNo = id;}// Getterint getRollNo(){return rollNo;}};int main(){Student obj;obj.setRollNo(123);cout << obj.getRollNo();return 0;}
In this example, we have a Student
class with a private member variable rollNo
in line 8. Since we cannot directly access rollNo
outside the Student
class, the public functions setRollNo
and getRollNo()
are used.