Is there a way to automatically generate getters and setters if they aren't present in C++?

user142019 picture user142019 · Aug 2, 2011 · Viewed 40.8k times · Source

I'm experienced with Objective-C, and in Objective-C you can let the compiler generate getters and setters for you if they aren't already present (@synthesize).

Is there a way to do this in C++, or do I need to implement all getters and setters myself?

Answer

Konrad Rudolph picture Konrad Rudolph · Aug 2, 2011

The C++ Core Guidelines advise against using trivial getters and setters because they’re unnecessary and a symptom of bad object-oriented design. As such, C++ has no built-in functionality for auto-generating getters and setters (though metaclasses, if they ever get included in the language, would make this possible). This is related to the well-established software engineering principle tell, don’t ask.

In particular, mutating state via setters is usually a sign of code smell and a bad architectural design. There are exceptions from this rule, purely out of practicality. And this is fine, but the exceptions are few enough that they shouldn’t warrant tools to auto-generate getters and setters.

In fact, you may use this as a litmus test: whenever you find yourself wishing for a tool to autogenerate such boilerplate, take a step back and reconsider your code design.


That said, there exist a number of tools to provide the functionality and in purely practical terms they may prove useful, though I have not personally tested them: