Nguyễn Tấn Phát
PRO
last year
Nguyễncountry asked

We use public getters and setters to work with private variables. Wouldn't it save time if we use public variables in the first place instead of getter and setter?

Kelish Rai
Expert
last year
Kelish Rai answered

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).

C++
This question was asked as part of the Learn C++ OOP course.