Topic 53 of 83
Getters & Setters
Overview
Getters (Accessors) and Setters (Mutators) are public methods used to read and update private variables. They allow the class to enforce rules and validation whenever data is accessed or changed.
Syntax
cpp
class User {
private:
string password;
public:
// Setter
void setPassword(string pwd) {
if (pwd.length() >= 8) {
password = pwd;
}
}
// Getter
string getPassword() const {
return password;
}
};Common Pitfalls
- Writing a getter/setter for *every single* private variable blindly. If a variable is truly internal, it shouldn't have public accessors at all.
Interview Tips
- Always mark getters as `const` (e.g., `int getAge() const;`). This tells the compiler the method will not modify the object, allowing getters to be called on `const` object instances.
Real-World Example
Using getters/setters for data validation.
example
cpp
#include <iostream>
using namespace std;
class Employee {
private:
int salary;
public:
void setSalary(int s) {
if (s >= 30000) {
salary = s;
} else {
cout << "Invalid salary.\n";
}
}
int getSalary() const {
return salary;
}
};
int main() {
Employee emp;
emp.setSalary(20000); // Fails validation
emp.setSalary(50000); // Succeeds
cout << emp.getSalary() << endl;
return 0;
}