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
EasyLet'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 aPlayerclass that manages a game character's profile with protected data access. Your class should have:- Private members:
name(string),level(int), andexperience(int) - A constructor that takes a name and initializes
levelto1andexperienceto0 - 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 exceeds100, 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 (always100 - current experience)
Mark all getters as
constsince they don't modify the object.- Private members:
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
Playerwith 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>"
- Create a
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
constsince they don't modify the object - Setters cannot be
constas 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;
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesC++ Build & CompilationHeader Files & Source FilesNamespaces & ScopeIntroduction to OOP in C++Classes vs ObjectsThe 'this' PointerMethods (Member Functions)Attributes (Data Members)Ctors & Dtors BasicsRecap - Simple Calculator4Class Properties
Instance vs Static MembersGetters and SettersConst Member FunctionsMutable KeywordStatic Methods and VariablesFriend Functions & ClassesRecap - Bank Account Manager7Inheritance
Basic InheritanceInheritance Access LevelsCtor & Dtor Call OrderMethod OverridingVirtual Functions & VTableMultiple InheritanceVirtual InheritanceRecap - Employee Hierarchy2Memory Management
Stack vs Heap MemoryPointers and ReferencesDynamic Memory (new/delete)Smart Pointers in C++RAII in C++Recap - Dynamic Array Manager5Encapsulation
Access Specifiers in C++Access Specifiers In DepthInformation HidingStruct vs ClassNested & Inner ClassesRecap - Student Records System8Polymorphism
Compile vs Runtime PolymorphFunction OverloadingVirtual Functions RevisitedPure Virtual FunctionsAbstract ClassesInterface Design in C++Dynamic Casting & RTTIRecap - Shape Calculator3Constructors & Destructors
Default ConstructorParameterized ConstructorCopy ConstructorMove ConstructorConstructor Init ListsDelegating ConstructorsDestructor Deep DiveRule of Three / Five / ZeroRecap - String Class6Operator Overloading
Intro to Operator OverloadArithmetic Operator OverloadComparison Operator OverloadStream OperatorsAssignment Operator Overload[] and () Operator OverloadType Conversion OperatorsRecap - Matrix Class9Templates
Function TemplatesClass TemplatesTemplate SpecializationVariadic TemplatesSFINAE & Type Traits BasicsRecap - Generic Container