C++
Getters and setters
Learn controlled access with getters and setters.
Getters and setters
Methods that provide controlled access to private members are called getters and setters. A getter reads, a setter writes. The name is usually derived from the member with a get or set prefix: getName(), setName().
Example: class Student { private: std::string name; public: std::string getName() { return name; } void setName(std::string n) { name = n; } };. The getter returns name; the setter assigns to name. Validation can be added in the setter: if (!n.empty()) name = n;. This prevents an empty name. This pattern is the standard way of encapsulation.
Validation in setters
The power of a setter is that it can check before writing. With direct assignment you could not check. Inside the setter you test the parameter and only assign to the member variable if it is valid.
Example: void setAge(int a) { if (a >= 0 && a <= 150) age = a; }. This setter rejects ages outside the 0–150 range. The calls setAge(-5) or setAge(200) do not change age. This keeps the object consistent at all times. Setters can also add edge-case logging or throw errors.
Exercise Add a getter and setter to the Student class
Define a Student class. Under private: add int age;. Under public: add int getAge() { return age; } and void setAge(int a) { if (a >= 0) age = a; }. In main create an instance, call setAge(20) and setAge(-5), then print getAge() with std::cout.
Show example solution
#include <iostream>
class Student {
int age;
public:
int getAge() {
return age;
}
void setAge(int a) {
if (a >= 0) age = a;
}
};
int main() {
Student s;
s.setAge(20);
s.setAge(-5);
std::cout << s.getAge();
return 0;
}
Test yourself
-
Complete the getter name
std::string get____() { return name; }
Show answer
std::string getName() { return name; }
-
What does setAge(-5) do? (body: if (a >= 0 && a <= 150) age = a;)
void setAge(int a) { if (a >= 0 && a <= 150) age = a; }
- Sets age = -5
- Gives a compile error
- Does not change age
- Sets age = 0
Show answer
Does not change age — -5 is not in the 0–150 range, so age is not changed.
-
Match each method to its role
- getName()
- Read (getter)
- setName(n)
- Write (setter)
- if (a >= 0) age = a
- Validation
- private: int age;
- Hidden data
Next lesson: const methods