
By keeping variables private and using public getter and setter methods, we can control how the data is accessed or modified. This provides better security, flexibility, and maintainability in your code.
For example, you might want to add validation or extra logic inside a setter to ensure the value is correct before it's saved:
class Person {
private:
int age;
public:
int getAge() {
return age;
}
void setAge(int newAge) {
// Validation inside setter
if (newAge > 0) {
age = newAge;
}
}
};
int main() {
Person p;
p.setAge(25); // Setting age via setter
cout << p.getAge(); // Getting age via getter
}Here, we ensure that age can never be set to a negative value.
If we had made age public, anyone could do something like p.age = -5;, which would break the logic of the program.
Simply put,
Private variables protect the integrity of the data.
Getters and setters allow you to add rules (like validation) easily without changing how other parts of your code use the class.
It also follows the principle of encapsulation — one of the four main principles of object-oriented programming (OOP).
Our Experts
Sudip BhandariHead of Growth/Marketing
Apekchhya ShresthaSenior Product Manager
Kelish RaiTechnical Content Writer
Abhilekh GautamSystem Engineer
Palistha SinghTechnical Content Writer
Sarthak BaralSenior Content Editor
Saujanya Poudel
Abhay Jajodia
Nisha SharmaTechnical Content Writer
Udayan ShakyaTechnical Content Writer