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 hardly ever use getters and setters in my own code. Veefu's answer looks good to me.
If you insist on having getters and/or setters, you can use macros to cut down on the boiler-plate.
#define GETTER(T,member) const T& Get##member() const { return member; }
#define SETTER(T,member) void Set##member(const T & value) { member = value; }
class Foo
{
public:
GETTER(std::string, bar)
SETTER(std::string, bar)
private:
std::string bar;
}
If you are developing COM components then yes, it is very popular.
Getting and setting data members qua data members: Bad.
Getting and setting elements of the abstraction: Good.
The arguments against Get/Set in terms of API design in the banking example are spot on. Dont expose fields or properties if they will allow users to break your business rules.
However, once you have decided that you do need a field or property, always use a property.
The automatic properties in c# are very easy to use, and there are many scenarios (databinding, serialization, etc) that do not work with fields, but require properties.
get and set are a pain inflicted upon people if you have to use them in any language.
Eiffel has it alot better where all that differs is the amount of information you have to provide to get the answer - a function with 0 parms is the same as accessing a member variable, and you can change freely between them.
When you control both sides of an interface the definition of the interface doesn't seem like such a big issue. However when you want to change implementation details and it inflicts the recompilation of client code as is the common case in C++ you wish to be able to minimise this as much as possible. As such pImpl and get/set would get used more in public APIs to avoid such damage.
Yes , get and set are popular in the c++ world.