C++ does not offer any kind of functionality for that, unfortunately, you have to write the getters and setters manually.
Since the language offers no kind of support for this kind of thing, there are a few rules of thumb you need follow to produce better quality code:
All member variables should be non-public. If they need to be accessed, write a getter and/or setter. This allows you to easily modify how that variable is accessed later on, without too much trouble.
Only members that are part of the interface (i.e.: which need to be visible) should have getters/setters. Don't start writing a getter/setter pair for every member in your class and call it encapsulation, 'cause it's not.
If you need a setter or a getter for a variable, it doesn't automatically mean you need the other as well. In principle, only add something if you need it: it's easy to add new things, but it's hard to remove them once you already have code that uses that feature.
In general, here's how getters and setters work in C++:
class Person
{
public:
const std::string& name() const {
return name_;
}
void name(const std::string& name) {
name_ = name;
}
private:
std::string name_;
};
int main()
{
Person pers;
pers.name("John");
std::cout << pers.name();
return 0;
}
A lot of people like to name those functions getName()
and setName()
, but I prefer to have it like this. Also remember to always make your getters const
(eg.: at the end of const std::string& name() const
) — this will signal to the compiler that the function won't modify the Person
object.
Edit: As you can see, in C++ getters and setter are just like any other method, there's absolutely nothing special about them.