I\'m from the world of C# originally, and I\'m learning C++. I\'ve been wondering about get and set functions in C++. In C# usage of these are quite popular, and tools like
I'd argue that providing accessors are more important in C++ than in C#.
C++ has no builtin support for properties. In C# you can change a public field to a property mostly without changing the user code. In C++ this is harder.
For less typing you can implement trivial setters/getters as inline methods:
class Foo
{
public:
const std::string& bar() const { return _bar; }
void bar(const std::string& bar) { _bar = bar; }
private:
std::string _bar;
};
And don't forget that getters and setters are somewhat evil.
Get and Set methods are useful if you have constraints in a variable value. For example, in many mathematical models there is a constraint to keep a certain float variable in the range [0,1]. In this case, Get, and Set (specially Set) can play a nice role:
class Foo{
public:
float bar() const { return _bar; }
void bar(const float& new_bar) { _bar = ((new_bar <= 1) && (new_bar >= 0))?new_bar:_bar; } // Keeps inside [0,1]
private:
float _bar; // must be in range [0,1]
};
Also, some properties must be recalculated before reading. In those cases, it may take a lot of unnecessary computing time to recalculate every cicle. So, a way to optimize it is to recalculate only when reading instead. To do so, overload the Get method in order to update the variable before reading it.
Otherwise, if there is no need to validade input values, or update output values, making the property public is not a crime and you can go along with it.