CodeBlanks Logo Icon CodeBlanks

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.

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

Starter code

main.cpp
#include <iostream>

// Define the Student class here

int main() {
    // Create a Student instance, call setAge and print getAge
    return 0;
}

Sample solution

main.cpp
#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;
}

Expected output

20

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the getter name

Question
std::string get____() { return name; }
Answer
std::string getName() { return name; }

Explanation: The getter name is get + member name (PascalCase): getName().

2 What does setAge(-5) do? (body: if (a >= 0 && a <= 150) age = a;)

main.cpp
void setAge(int a) { if (a >= 0 && a <= 150) age = a; }
  • Sets age = -5
  • Gives a compile error
  • Does not change age Correct answer
  • Sets age = 0

Explanation: -5 is not in the 0–150 range, so age is not changed.

3 Match each method to its role

Term Meaning
getName() Read (getter)
setName(n) Write (setter)
if (a >= 0) age = a Validation
private: int age; Hidden data

All lessons in Intermediate