Start learning free

LESSON 593 OF 634 · OBJECT-ORIENTED PROGRAMMING

Getters and Setters in C++ in C++

Lesson

TL ; DR:

A getter reads a private field. A setter changes it, but only to a value the class allows.

C++ has no special syntax for them. The getter is a method getAge(). The setter is a method setAge(value). Both are public, and both use the private field age.


class Dog {
private:
    int age;

public:
    Dog(int age) { this->age = age; }

    int getAge() {
        return age;
    }

    void setAge(int value) {
        if (value >= 0) {
            age = value;
        }
    }
};


Full lesson:

In the Access Modifiers lesson, getName() let other code read a private field. Often other code must change a field too. A setter allows that, and it checks each new value first.

The getter

The getter returns the private field. Other code calls rex.getAge() to read the age.

The setter

The setter gets the new value as a parameter. Other code calls rex.setAge(4) to change the age.

The field stays under private. The two methods go under public.

The rule

A dog's age can't be negative. So setAge changes age only when value is 0 or more. After rex.setAge(-5), the age stays as it was.

Why not a public field?

With a public age field, any code could set it to -5. Nothing would check it. The setter keeps the rule inside the class.


Your task

The Dog class keeps its age in the private field age. Add two public methods. The getter getAge() returns the age. The setter setAge(value) ignores negative values.

The code in mainFunction creates rex, then reads and sets its age.

Expected output:

Rex is 3
Rex is still 3
Rex is 4
STEP 1 OF 3
    Ctrl + Enter to check

    Getters And Setters in C++

    Keep going with C++500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free