Encapsulation, Getters & Setters
Overview
Encapsulation is the defensive shield of OOP. By making all class data private, you physically prevent external developers (or yourself, a month from now) from making catastrophic errors, like setting a Player's health to -5000 or altering a secure bankBalance directly.
However, other parts of the program still need to interact with that data. To solve this securely, we use Getters and Setters (also known as Accessors and Mutators). These are perfectly controlled public functions that act as gatekeepers. They allow external code to request data (Get) or change data (Set), but strictly on YOUR terms, allowing you to run validation logic before applying any changes.
Syntax
#include <iostream>
#include <string>
class Employee {
private:
// SHIELDED DATA
double salary;
public:
// CONSTRUCTOR
Employee() : salary(50000) {}
// GETTER: Allows read-only access
double getSalary() {
return salary;
}
// SETTER: Allows modification, but enforces strict validation!
void setSalary(double newSalary) {
if (newSalary < 0) {
std::cout << "Error: Salary cannot be negative!\n";
} else {
salary = newSalary; // Only updates if valid!
}
}
};
int main() {
Employee emp;
// emp.salary = -999; // ERROR: Private!
emp.setSalary(-999); // Denied by validation!
emp.setSalary(60000); // Accepted!
std::cout << "Salary: $" << emp.getSalary() << "\n";
return 0;
}Common Pitfalls
- Writing Setters that do no validation. If you write
void setHP(int h) { hp = h; }, you have effectively made the variablepublic, defeating the entire purpose of Encapsulation. Setters should almost always includeifstatements verifying the incoming data.
Interview Questions
const keyword to the end of a Getter function (e.g., double getSalary() const { return salary; })?Appending const to the end of a method mathematically guarantees to the compiler that this specific method will NEVER modify any internal class variables. It is purely read-only. This allows the compiler to optimize the code heavily and allows constant Objects to call the getter securely.
Real-World Example
Using 'const-correct' Getters and highly secure Setters in a production environment.
#include <iostream>
#include <string>
class User {
private:
std::string password;
public:
User(std::string pass) : password(pass) {}
// The 'const' guarantees this function will not mutate the Object
std::string getPassword() const {
return "********"; // Hiding the actual data for security!
}
void updatePassword(std::string oldPass, std::string newPass) {
if (oldPass == password && newPass.length() >= 8) {
password = newPass;
std::cout << "Password Updated.\n";
} else {
std::cout << "Update Failed. Invalid credentials.\n";
}
}
};Check Your Knowledge
Test your understanding of Encapsulation, Getters & Setters with these quick questions.