0
0
C++programming~5 mins

Getter and setter methods in C++

Choose your learning style9 modes available
Introduction

Getter and setter methods help us safely get or change the value of a private variable in a class.

When you want to control how a variable is read or changed.
When you want to hide the details of how data is stored inside a class.
When you want to check or change values before saving them.
When you want to keep variables private but still allow access.
When you want to make your code easier to maintain and understand.
Syntax
C++
class ClassName {
private:
    DataType variable;
public:
    DataType getVariable() {
        return variable;
    }
    void setVariable(DataType value) {
        variable = value;
    }
};

Getter methods usually start with get and return the variable's value.

Setter methods usually start with set and take a parameter to update the variable.

Examples
This example shows a getter and setter for age. The setter checks that age is not negative before setting it.
C++
class Person {
private:
    int age;
public:
    int getAge() {
        return age;
    }
    void setAge(int a) {
        if (a >= 0) {
            age = a;
        }
    }
};
Here, the setter ensures the balance cannot be set to a negative number.
C++
class BankAccount {
private:
    double balance;
public:
    double getBalance() {
        return balance;
    }
    void setBalance(double b) {
        if (b >= 0) {
            balance = b;
        }
    }
};
Sample Program

This program creates a Car object, sets its speed to 50, then tries to set it to -10. The setter prevents negative speed by setting it to 0 instead.

C++
#include <iostream>
using namespace std;

class Car {
private:
    int speed;
public:
    int getSpeed() {
        return speed;
    }
    void setSpeed(int s) {
        if (s >= 0) {
            speed = s;
        } else {
            speed = 0;
        }
    }
};

int main() {
    Car myCar;
    myCar.setSpeed(50);
    cout << "Speed is: " << myCar.getSpeed() << " km/h" << endl;
    myCar.setSpeed(-10); // invalid speed
    cout << "Speed after invalid set: " << myCar.getSpeed() << " km/h" << endl;
    return 0;
}
OutputSuccess
Important Notes

Always keep variables private to protect data.

Use setters to add checks before changing values.

Getters let you read values without changing them.

Summary

Getter and setter methods control access to private variables.

Setters can check values before saving them.

Getters return the current value safely.