OOP: ACCESS SPECIFIERS
Getter and Setter Functions
Getters and setters are public methods that control access to private data.
Getter
A getter reads private data.
int getSalary() const;
Setter
A setter writes private data, usually with validation.
bool setSalary(int amount);
Example
#include <iostream>
#include <string>
class Employee {
private:
std::string name;
int salary = 0;
public:
explicit Employee(const std::string& employeeName) : name(employeeName) {}
const std::string& getName() const {
return name;
}
int getSalary() const {
return salary;
}
bool setSalary(int amount) {
if (amount < 0) {
return false;
}
salary = amount;
return true;
}
};
int main() {
Employee employee("Mina");
if (!employee.setSalary(-500)) {
std::cout << "Invalid salary rejected\n";
}
employee.setSalary(55000);
std::cout << employee.getName() << ": $" << employee.getSalary() << '\n';
}
Why Return bool From Setter?
Returning bool tells the caller whether the update succeeded.
This is cleaner than silently ignoring invalid data.
Do We Need Getter and Setter for Everything?
No.
Do not automatically create getters and setters for every private member.
Ask:
- Should outside code read this data?
- Should outside code modify this data?
- Should modification require validation?
- Is a behavior method better than exposing data?
Example:
account.withdraw(500);
This is better than:
account.setBalance(account.getBalance() - 500);
Viva Answer
A getter is a public method that reads private data. A setter is a public method that modifies private data, usually after validation. Getters and setters should be added only when they support a safe class interface.
Quick Check
- What is a getter?
- What is a setter?
- Why validate inside setters?
- Should every private variable automatically have a setter?