Ready to practice?
Sign up to access interactive coding exercises and track your progress.
Getters and Setters for Class Members
Provide controlled access to private data through getter and setter functions.
Access Functions
When class members are private, you need public functions to access them. These are called access functions (or accessor functions).
Getters
A getter (accessor) retrieves a private member's value:
class Item
{
private:
int value{};
public:
int getValue() const
{
return value;
}
};
Getters typically:
- Start with "get" (though some omit it:
value()instead ofgetValue()) - Are marked
const(they don't modify the object) - Return the member's value
Setters
A setter (mutator) modifies a private member's value:
class Item
{
private:
int value{};
public:
void setValue(int newValue)
{
if (newValue >= 0)
value = newValue;
}
int getValue() const
{
return value;
}
};
Setters typically:
- Start with "set"
- Take a parameter (the new value)
- Validate input before updating the member
Why use access functions?
Validation: Prevent invalid values.
class Health
{
private:
int points{};
public:
void setPoints(int p)
{
if (p >= 0 && p <= 100)
points = p;
}
int getPoints() const
{
return points;
}
};
Computed values: Return calculated results instead of stored values.
class Zone
{
private:
int width{};
int height{};
public:
int getArea() const // Computed, not stored
{
return width * height;
}
void setWidth(int w) { width = w; }
void setHeight(int h) { height = h; }
};
Side effects: Perform actions when values change.
class EventDispatcher
{
private:
int eventCount{};
public:
void setEventCount(int count)
{
eventCount = count;
std::cout << "Event count updated to " << count << '\n';
}
int getEventCount() const
{
return eventCount;
}
};
Future flexibility: Change internal representation without breaking code.
// Version 1: Store raw damage
class Weapon
{
private:
int damage{};
public:
int getDamage() const { return damage; }
void setDamage(int d) { damage = d; }
};
// Version 2: Store damage with modifier (interface unchanged!)
class Weapon
{
private:
int baseDamage{};
double modifier{ 1.0 };
public:
int getDamage() const { return static_cast<int>(baseDamage * modifier); }
void setDamage(int d) { baseDamage = d; }
};
Trivial access functions
Sometimes getters and setters do nothing special:
class DataStore
{
private:
int data{};
public:
int getData() const { return data; }
void setData(int d) { data = d; }
};
If there's no validation, computation, or side effects, why bother? Because you might add them later. Access functions provide future flexibility.
When to omit access functions
Not every private member needs getters and setters. Only provide them when external code needs access:
class Inventory
{
private:
std::string ownerName{}; // Has get/set
std::vector<int> itemIds{}; // No direct get/set (implementation detail)
bool isLocked{}; // Has getter only
public:
void setOwnerName(const std::string& name) { ownerName = name; }
std::string getOwnerName() const { return ownerName; }
bool getIsLocked() const { return isLocked; }
// No getters/setters for 'itemIds' - it's internal
};
Naming conventions
Standard style:
int getDamage() const;
void setDamage(int dmg);
Property-style (less common in C++):
int damage() const; // Getter
void damage(int dmg); // Setter (overloaded)
Boolean getters:
bool isAlive() const; // Preferred
bool getIsAlive() const; // Also acceptable
Use "is", "has", or "can" for boolean queries.
Make getters const since they shouldn't modify the object. Validate in setters by checking inputs before storing them. Return by const reference for large objects to avoid expensive copies. Don't provide setters for values that shouldn't change after construction - only initialize them in the constructor. Consider read-only properties where you provide a getter but no setter when external code should observe but not modify a value.
class Timer
{
private:
long startTick{};
long currentTick{};
public:
void start();
void update();
long getElapsed() const { return currentTick - startTick; }
// No setElapsed() - computed read-only property
};
Summary
Getters and setters: Getters (accessor functions) retrieve private member values, while setters (mutator functions) modify them. Getters are typically marked const and return values, while setters validate input before storing.
Validation: Access functions enable input validation, preventing invalid values from being stored. This ensures objects maintain valid states throughout their lifetime.
Computed values: Getters can return calculated results instead of stored values, allowing you to change internal representation without affecting the public interface.
Side effects: Setters can perform additional actions when values change, such as logging, triggering events, or updating related data.
Naming conventions: Standard style uses getX() and setX() prefixes. Boolean getters often use is, has, or can prefixes (isAlive(), hasAmmo(), canAttack()).
Access functions are the primary mechanism for controlled access to private data, enabling encapsulation while providing necessary functionality to class users. By carefully designing which members have getters, setters, or both, you create intuitive and safe class interfaces.
Getters and Setters for Class Members - Quiz
Test your understanding of the lesson.
Practice Exercises
Getters and Setters
Implement access functions (getters and setters) to provide controlled access to private data.
Lesson Discussion
Share your thoughts and questions
No comments yet. Be the first to share your thoughts!