2

Often I want to create member variables that are modifiable by the class, but unmodifiable by other outside classes. The way I do this is by making the member private, and then making a public getter function. This seems like extra work. Is there a simpler way of doing this?

einpoklum
  • 118,144
  • 57
  • 340
  • 684

1 Answers1

1

No, there isn't a simpler way to this. Sorry... Remember that in C++ it's often the case that implementing a certain idiom takes some length and can get somewhat ugly, but in exchange you get more straightforward and elegant use.

What you can do is create a struct of all of these members of your class, and then at least not have to implement a separate getter for each of them - just use a getter for the struct which returns a const&.

Also (1): Follow @JohnFilieau's suggestion, so that the member is named, say myclass::foo_ and the getter is named myclass::foo(), which doesn't make the implementation simpler, but makes the use more readable.

Also (2): You could create a mix-in template for such a member (or several members, using a variadic template pack), and then inherit from it. Of course that might complicate your construction and perhaps other methods somewhat.

einpoklum
  • 118,144
  • 57
  • 340
  • 684