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?
-
You can make them `const`. – Eljay Mar 24 '20 at 22:53
-
Making a member variable `const` will cause your default assignment operator to be deleted, so be careful with this. You'll need a custom `operator=` (or just not assign at all, which might be desirable) – JohnFilleau Mar 24 '20 at 22:55
-
1I don't believe there is a simpler way in C++. (Making them const would mean the class won't be able to modify them either) – Jeremy Friesner Mar 24 '20 at 22:56
-
1@Eljay: That doesn't do what OP asked for. – einpoklum Mar 24 '20 at 22:57
-
If it helps, name your getter function for variable `x`, just `x()`, not `getx()`. It looks neater. It's certainly a style thing, but I don't like exposing any of my member variable as public ever. It's only functions for interface. – JohnFilleau Mar 24 '20 at 22:59
-
how about declaring the instance as const? – Midnight Exigent Mar 24 '20 at 23:08
-
@einpoklum • The OP's description doesn't match the OP's title's question. – Eljay Mar 25 '20 at 00:40
1 Answers
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.

- 118,144
- 57
- 340
- 684
-
Great. I was actually creating and returning structs already, but I wasn't sure if this was a best practice. – Free-Time-Jaeger Mar 24 '20 at 23:17