Getters And Setters
Lesson 30Last Updated : November, 2022
In C++, getters and setters are member functions used to access and modify the private data members of a class, respectively.
Getters are functions that are used to retrieve the value of a private data member of a class. Setters, on the other hand, are functions that are used to set the value of a private data member of a class. The main purpose of getters and setters is to enforce encapsulation in object-oriented programming, which means that the internal state of an object should be hidden from the outside world.
Here’s an example of how getters and setters can be implemented in C++:
#include <iostream>
#include <string>
class Person {
public:
// constructor
Person(std::string n, int a) {
name = n;
age = a;
}
// getters
std::string getName() {
return name;
}
int getAge() {
return age;
}
// setters
void setName(std::string n) {
name = n;
}
void setAge(int a) {
age = a;
}
private:
std::string name;
int age;
};
int main() {
// create object using constructor
Person p1("Alice", 25);
// call setters to modify object data
p1.setName("Bob");
p1.setAge(30);
// call getters to retrieve object data
std::cout << "Name: " << p1.getName() << std::endl;
std::cout << "Age: " << p1.getAge() << std::endl;
return 0;
}
In this example, we define a Person
class with two private data members name
and age
. We also define four member functions, two getters (getName
and getAge
) and two setters (setName
and setAge
), which are used to access and modify the private data members of the Person
class.
In the main function, we create an object p1
of the Person
class using the parameterized constructor. We then call the setName
and setAge
setters on the p1
object to change its name
and age
data members. Finally, we print the values of these data members using the getName
and getAge
getters.
Getters and setters are important tools for enforcing encapsulation and ensuring that private data members are only accessed and modified in a controlled way, which can help prevent bugs and make our code more modular and easier to maintain.