0

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

Luís Guilherme
  • 2,620
  • 6
  • 26
  • 41
  • The reasons in C++ aren't really different from other languages; see [Why use getters and setters?](http://stackoverflow.com/questions/1568091/why-use-getters-and-setters) – Michael Mrozek Jul 30 '10 at 16:34
  • Possible duplicate of [Why use getters and setters/accessors?](https://stackoverflow.com/questions/1568091/why-use-getters-and-setters-accessors) – Guillaume D Jun 14 '19 at 09:09

4 Answers4

3

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.

1

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
  • 4,928
  • 4
  • 26
  • 39
0

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
  • 101,701
  • 37
  • 181
  • 258
  • That's a POD and usually not implemented as a class but as a struct. –  Jul 30 '10 at 16:34
  • 2
    You are talking about a POD right ? In those cases, usually a struct reads better, doesnt it ? – Tom Jul 30 '10 at 16:34
0

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.

Michael Spector
  • 36,723
  • 6
  • 60
  • 88