In almost all cases when you think you need to create a setter AND getter (that is, both at the same time), your design is wrong.
Think about the purpose of num_chests ? You cannot go anywhere without knowing what it is.
According to your code, I assume that it contains the number of chests per level. In this case, you do not want to provide a setter for this value for everyone. You want the value to be equal to the number of chests in the game, and by providing a setter, anyone can annul this invariant.
Instead, you can provide ONLY a getter, and you can control its value in your class.
class Chest : public GameObject { public: Chest() { ++num_chests_; } ~Chest() { --num_chests_; } static int num_chests() { return num_chests_; } private: static int num_chests_; }; int Chest::num_chests_ = 0;
More explanations on why getters and setters are the wrong decision in my opinion. If you provide setter and getter, you only have the illusion of control over a variable. Consider std::complex . Why
std::complex<double> my_complex(1.0, 5.0); my_complex.real(my_complex.real()+1);
it's better
std::complex<double> my_complex(1.0, 5.0); my_complex.real()++;
Answer: when std::complex was developed, there were no references to C ++. In addition, Java has no C ++ references, so they must write boilerplate code everywhere. Now GCC returns non-constant links here as an extension, and C ++ 11 allows
reinterpret_cast<double (&)[2]>(non_const_non_volatile_complex_variable)[0]
and
reinterpret_cast<double (&)[2]>(non_const_non_volatile_complex_variable)[1]
as a valid way to access the real and imaginary parts of std::complex<value> .