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
In your example:
class Foo
{
public:
const std::string GetBar(); // Should this be const, not sure?
You probably mean this:
std::string GetBar() const;
Putting the const
at the end means "This function doesn't modify the Foo instance it is called on", so in a way it marks it as a pure getter.
Pure getters occur frequently in C++. An example in std::ostringstream
is the str()
function. The Standard library often follows a pattern of using the same function name for a pair of getter/setter functions - str
being an example again.
As to whether it's too much work to type out, and is it worth it - that seems an odd question! If you need to give clients access to some information, provide a getter. If you don't, then don't.