Luís Guilherme
Luís Guilherme

Reputation: 2719

Getters and Setters in C++

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

Upvotes: 0

Views: 961

Answers (4)

user395760
user395760

Reputation:

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.

Upvotes: 3

Michael Spector
Michael Spector

Reputation: 37019

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.

Upvotes: 0

James Curran
James Curran

Reputation: 103575

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.

Upvotes: 0

Jordan
Jordan

Reputation: 5058

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.

Upvotes: 1

Related Questions