Menu
Coddy logo textTech

Getters and Setters

Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 28 of 104.

When class members are private, external code cannot access them directly. Getters and setters are public methods that provide controlled access to these private members - getters retrieve values, setters modify them.

class Temperature {
    double celsius;    // Private - cannot be accessed directly
    
public:
    // Getter - returns the value
    double getCelsius() const {
        return celsius;
    }
    
    // Setter - modifies the value with validation
    void setCelsius(double value) {
        if (value >= -273.15) {    // Absolute zero check
            celsius = value;
        }
    }
};

The real power of setters is validation.

Instead of allowing any value to be assigned, you can enforce rules. In the example above, temperatures below absolute zero are rejected. Without a setter, anyone could assign invalid data directly.

Getters can also transform data before returning it:

class Temperature {
    double celsius;
public:
    double getCelsius() const { return celsius; }
    
    // Computed getter - doesn't store fahrenheit, calculates it
    double getFahrenheit() const {
        return celsius * 9.0 / 5.0 + 32.0;
    }
    
    void setCelsius(double value) { celsius = value; }
};

Notice the const keyword on getters - this indicates they don't modify the object. Setters cannot be const since their purpose is to change member values. This pattern of using getters and setters is fundamental to encapsulation, giving you full control over how your class data is accessed and modified.

challenge icon

Challenge

Easy

Let's build a player profile system that demonstrates how getters and setters provide controlled access to private data, including validation and computed properties.

You'll create two files to organize your code:

  • Player.h: Define a Player class that manages a game character's profile with protected data access. Your class should have:
    • Private members: name (string), level (int), and experience (int)
    • A constructor that takes a name and initializes level to 1 and experience to 0
    • A getter getName() that returns the player's name
    • A getter getLevel() that returns the current level
    • A getter getExperience() that returns current experience points
    • A setter setName() that only accepts names with at least 3 characters — if invalid, keep the current name unchanged
    • A setter addExperience(int points) that only accepts positive values. When experience reaches or exceeds 100, the player levels up: increment level by 1 and subtract 100 from experience. This can happen multiple times if enough experience is added.
    • A computed getter getExperienceToNextLevel() that returns how many more experience points are needed to reach the next level (always 100 - current experience)

    Mark all getters as const since they don't modify the object.

  • main.cpp: Demonstrate your getters and setters in action. Read a player name and experience points to add from input (each on a separate line), then:
    • Create a Player with the input name
    • Print "Player: <name>, Level: <level>, XP: <experience>"
    • Add the input experience points using addExperience()
    • Print the same status line again to show the updated state
    • Print "XP to next level: <amount>"
    • Try to change the name to "Al" (should fail validation)
    • Print "Name after invalid change: <name>"
    • Change the name to "Champion" (should succeed)
    • Print "Name after valid change: <name>"

The experience input will be provided as a string that you'll need to convert to an integer. Include your header file in main.cpp using #include "Player.h".

Cheat sheet

Getters and setters are public methods that provide controlled access to private class members.

Basic getter and setter pattern:

class Temperature {
    double celsius;    // Private member
    
public:
    // Getter - returns the value (marked const)
    double getCelsius() const {
        return celsius;
    }
    
    // Setter - modifies the value
    void setCelsius(double value) {
        celsius = value;
    }
};

Setters with validation:

void setCelsius(double value) {
    if (value >= -273.15) {    // Validate before setting
        celsius = value;
    }
}

Computed getters:

// Returns calculated value without storing it
double getFahrenheit() const {
    return celsius * 9.0 / 5.0 + 32.0;
}

Key points:

  • Getters should be marked const since they don't modify the object
  • Setters cannot be const as they change member values
  • Setters enable validation to prevent invalid data
  • Getters can transform or compute values before returning them

Try it yourself

#include <iostream>
#include <string>
#include "Player.h"

using namespace std;

int main() {
    // Read player name
    string playerName;
    getline(cin, playerName);

    // Read experience points to add (as string, convert to int)
    string expString;
    getline(cin, expString);
    int expToAdd = stoi(expString);

    // TODO: Create a Player with the input name

    // TODO: Print initial status: "Player: <name>, Level: <level>, XP: <experience>"

    // TODO: Add the input experience points using addExperience()

    // TODO: Print the updated status line

    // TODO: Print "XP to next level: <amount>"

    // TODO: Try to change the name to "Al" (should fail validation)

    // TODO: Print "Name after invalid change: <name>"

    // TODO: Change the name to "Champion" (should succeed)

    // TODO: Print "Name after valid change: <name>"

    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming