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 4Free plan: 30 tutor messages. Premium is unlimited.
