Return by reference or create a typical setter/getter?

c++

Solution

Unless you feel very strongly against it, use getter and setter member functions.

The reason `int& num_chests()` or a public field is bad is that you are coupling client code that uses the `num_chests` value to the fact that it is actually a field (an internal implementation detail).

Suppose that later you decided you would have a `std::vector<Chest> chests` private field in your class. Then you wouldn't want to have a `int num_chests` field -- it's horribly redundant. You would want to have `int num_chests() { return chests.size(); }`.

If you were using a public field, now all of your client code needs to use this function instead of the previous field access -- every usage of the `num_chests` value needs to be updated, because the interface has changed.

If you were using a function that returns a reference, you now have a problem because `chests.size()` is a return by value -- you can't in-turn return that by reference.

Always encapsulate your data. It requires only a minimal amount of boilerplate code.

In response to comments saying you should just use public fields:

Keep in mind that the only benefit of using public fields (other than the remote possibility of some micro-optimization) is that you don't have to write the boilerplate code. "My teacher used to hate when I used public fields (and he was sooo annoying)" is a very poor argument for using public fields.

Problem

I was wondering about good practices in C++, and I was facing the problem of making a getter/setter for a class member. So, why don't simply return the member by reference so this way I can modify or access its value to read it? Specifically, this is my code: ``` class Chest : public GameObject { public: Chest(); ~Chest(); static int& num_chests(); private: static int num_chests_; }; ``` Is this a bad practice? Should I use these instead? ``` class Chest : public GameObject { public: Chest(); ~Chest(); static int num_chests(); static void set_num_chests(int num_chests); private: static int num_chests_; }; ```

Original source

Related problems