views:

50

answers:

4

Should I use getters and setters in C++ or is it better to access class data directly?

+1  A: 

It depends what your implementation is and what style you are going for. Part of the language design is to be able to use encapsulation so it would generally be good practice to use get and set methods to access the private data of a class.

Jordan
A: 

In general, getter & setter are better.

The exception is if you have a simple class -- generally meaning one without member functions -- which is just used to bundle data together so it can be passed around easier.

James Curran
That's a POD and usually not implemented as a class but as a struct.
delnan
You are talking about a POD right ? In those cases, usually a struct reads better, doesnt it ?
Tom
A: 

If there's no logic in getter/setter except for returning/assigning a value from/to a public field there's no significant difference between usage of getters/setters and accessing the field directly.

spektom
+2  A: 

The usual rationale for getters and setters is: You can change it from being a simple wrapper around a private field to a rather complex computation without breaking any code using the class. If you're sure the getters/setter will never be more than that (or it will never be used that much), feel free to use a pulic field, I don't mind.

delnan