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
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.