Last Updated : 27 May, 2024
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 GetterdataType getVariableName() const {Setters in C++
return variableName;
}
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 Settervoid setVariableName(dataType newValue) {C++ Program to Demonstrate the Use of Getter and Setter.
variableName = newValue;
}
The below example demonstrates how we can use getters and setters in C++.
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;
}
Explanation: In the above program, we have accessed the private member "salary" of class employee using the setter setSalary() method and getter getSalary() method.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4