Sometimes I need to expose some of the class members. For example in the following example class Mechanic
may need direct access to Engine
componen
Explicit getters and setters can be overly-bureaucratic; it depends on your situation.
The main cited reason for having getter and setter functions is that it isolates the clients of your class from potential changes in implementation in the future (for instance, consider what would happen if you decide to generate an Engine
object on demand (rather than using a member variable), or decide to hide it behind a smart pointer, or some other container).
If your class if very simple (e.g. close to being a POD) and unlikely to change, then it may not be worth the faff of having to implement the getters and setters.
However, to answer your question, a non-const getter probably doesn't make much sense. Your getter prototype should be Engine & engine() const
; otherwise you won't be able to call it on const
Car
objects.
I have found reasonable point to provide such getter. It makes integration of your software easier (for example, when you want to translate interface into another language and bind ABIs).
One advantage of providing a getter is that when and if you decide to change the way the getter works, the code that uses this class need not be recompiled. But if you have a public field and later decide to make a getter, all code should be recompiled. Other than that I don't see any serious practical reason to make your variable private. However note that this all holds if and only if you have to provide a way for outer users to get a reference to the Engine. If it is possible to design the software so that this need be eliminated at all, that would be better.
yes, it makes sense - for maintainability, validation, and consistency.
you may need to change many aspects of the class in the future, providing an accessor can help minimize breakage of client code.
you can enter all the validation logic you need here, to ensure that engine is a valid pointer, is not in an unusable state, etc.
finally, your code will be consistent: you won't have to open the header to know the member visibility - you just always know. this is also useful with templates.
For me it makes sense here:
image(i,j) = 234;
As I happened to get educated on recently, getters and setters smell of bad design. But, if you want it that way, providing functions to get and set m_engine
(Defined by you) rather than just exposing it (You have no intervention) means that you have a plug-in point for future changes.