Is there a way to automatically generate getters and setters if they aren't present in C++?
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:
- Visual Studio Code:
- Getter and Setter Generator
- Getter/Setter Generator
- Vim
- vim-refactor
- Emacs
- semantic-refactor
- Visual Studio
- Resharper C++
- Visual Assist
- GS Assist
- CLion
- built in
- Eclipse
- built into Exclipse CDT (“Implement method”)
Not the compiler itself, but an IDE like eclipse CDT can actually perform this action automatcally (right click on class > Source > Generate Getters and Setters...).
You have to implement them yourself