Class-Based Getters and Setters in C++

Class-Based Getters and Setters in C++ | Encapsulation Explained

🔑 Class-Based Getters and Setters in C++

In C++, getters and setters are class member functions used to access and modify private data members safely. This practice enforces encapsulation — one of the key principles of object-oriented programming.

📘 What are Getters and Setters?

Getters (or accessors) are functions that return the value of a private member variable. Setters (or mutators) set or update the value of that private variable. By using them, we prevent direct access to internal data, protecting the integrity of the object's state.

💡 Why Use Getters and Setters?

  • Control how data members are accessed or modified.
  • Validate input values before setting them.
  • Maintain encapsulation and data hiding.
  • Make your code easier to maintain and debug.

📄 C++ Example: Getters and Setters


#include <iostream>
using namespace std;

class Person {
private:
    string name;
    int age;

public:
    // Setter for name
    void setName(const string &newName) {
        name = newName;
    }

    // Getter for name
    string getName() const {
        return name;
    }

    // Setter for age with validation
    void setAge(int newAge) {
        if (newAge >= 0)
            age = newAge;
        else
            cout << "Invalid age!" << endl;
    }

    // Getter for age
    int getAge() const {
        return age;
    }
};

int main() {
    Person p;
    p.setName("Alice");
    p.setAge(30);

    cout << "Name: " << p.getName() << endl;
    cout << "Age: " << p.getAge() << endl;

    p.setAge(-5);  // Invalid age, won't update

    return 0;
}
    

📝 Sample Output

Name: Alice
Age: 30
Invalid age!

🧠 How It Works

  • The setName and setAge functions safely assign values to private variables.
  • setAge includes validation to prevent invalid negative ages.
  • getName and getAge provide controlled access to private members.
  • Direct access to name and age is restricted for data integrity.

This design pattern is essential for creating robust and maintainable C++ programs that respect the principles of encapsulation and data hiding.

Post a Comment

Post a Comment (0)

Previous Post Next Post

ads

ads

Update cookies preferences