Skip to content

Getters / Setters

Getters and Setters are public methods that provide controlled access to private data members.

Getter → reads a private variable. Setter → writes/modifies a private variable.

Why Not Just Make Members Public?

cpp
// BAD — public member, no control
class Player { public: int health; };
Player p; p.health = -9999; // invalid! no validation

// GOOD — private with getter/setter
class Player {
private: int health;
public:
    void setHealth(int h) {
        if (h < 0) h = 0;
        if (h > 100) h = 100;
        health = h;
    }
    int getHealth() { return health; }
};

Basic Example

cpp
class Person {
private:
    string name; int age;
public:
    string getName() { return name; }
    int getAge() { return age; }
    void setName(string n) { if (!n.empty()) name = n; }
    void setAge(int a) { if (a >= 0 && a <= 150) age = a; }
};

Read Only — Getter Only

cpp
class Circle {
private:
    const double radius;
    double area;
public:
    Circle(double r) : radius(r) { area = 3.14 * r * r; }
    double getRadius() { return radius; } // getter only — read only
    double getArea() { return area; }     // getter only — read only
};

Write Only — Setter Only

cpp
class SecureLogin {
private:
    string password;
public:
    void setPassword(string p) { // setter only
        if (p.length() >= 8) password = p;
    }
    // no getter — password can never be read directly
};

Getter Returning Reference — Dangerous!

cpp
int& getValueRef() { return value; } // dangerous!
d.getValueRef() = 999; // bypasses encapsulation!
// Always return by VALUE in getters unless you have specific reason

Const Getter — Best Practice

cpp
int getWidth() const { return width; }   // const getter
int getHeight() const { return height; } // const getter
// Mark getters as const — they don't modify the object
// const objects can only call const methods

Chaining Setters — Fluent Interface

cpp
class Builder {
    string name; int age; string city;
public:
    Builder& setName(string n) { name = n; return *this; }
    Builder& setAge(int a) { age = a; return *this; }
    Builder& setCity(string c) { city = c; return *this; }
};

Builder b;
b.setName("Alice").setAge(25).setCity("Delhi").show();

Lazy Initialization in Getter

cpp
string getData() const {
    if (!loaded) {
        data = "loaded from file"; // load only when needed
        loaded = true;
    }
    return data;
}

Summary Table

TypeGetterSetter
PurposeRead private dataWrite private data
ReturnsValuevoid (usually)
Keywordconst recommendednone
ValidationNot neededAdd here

Key Points

PointDetail
Always mark getterconst
Validation goesIn setter
Return byValue (not reference)
ChainingReturn *this from setter
Lazy initCan be done in getter

One-liner: "Getters and setters provide controlled access to private members — getters read data and should be const, setters write data and should validate input."