C++ Getters and Setters
In C++, getters and setters are part of data encapsulation used to protect our data, particularly when creating classes. These are public methods that are used to access and modify the private or protected members of a class. In this article, we will learn how to use getters and setters in C++.
Getters in C++
In C++, getters, also known as accessors (as they access the value), are the public member functions that are used to fetch private member’s values. In general, the getter starts with the word “get” followed by the variable name.
Syntax to Define Getter
dataType getVariableName() const {
return variableName;
}
Setters in C++
Setters, also known as mutators (as they update the value), are also the public member functions that set the value of a private member variable. In general, the setter starts with the word “set” followed by the variable name.
Syntax to Define Setter
void setVariableName(dataType newValue) {
variableName = newValue;
}
C++ Program to Demonstrate the Use of Getter and Setter.
The below example demonstrates how we can use getters and setters in C++.
// C++ program to demonstrate the use of getters and setters
#include <iostream>
using namespace std;
// Define Class Employee
class Employee {
private:
// Define Private member salary
int salary;
public:
// Setter
void setSalary(int s) { salary = s; }
// Getter
int getSalary() { return salary; }
};
int main()
{
// create object of class employee
Employee myObj;
// set the salary
myObj.setSalary(10000);
// get the salary and print it
cout << "Salary is: " << myObj.getSalary();
return 0;
}
Output
Salary is: 10000
Explanation: In the above program, we have accessed the private member “salary” of class employee using the setter setSalary() method and getter getSalary() method.
Contact Us