Answer to Public read-only data
With some clever use of references, it is possible to write like this:
class C { public: C() : data(myData), myData(0) {} void update() { myData++; } const int &data; private: int myData; };
The trick used here is that we initialize data
to refer to myData
.
Since data
is a reference to a const int
, the contents of myData
can not be modified through that reference. However, we can still do
anything we like to the myData
value.
There are some downsides to this implementation though:
- We lose our implicit copy and assignment operators because of the reference.
- We use more memory for each instance of the class. References are usually implemented by pointers internally, even though the compiler is free to do any way it feels like.
Because of this, I usually prefer the getter function variant. But this version is a fun extension of the language's rules.
Comments
New comment
You can use GitHub flavored markdown here. Parsed by Parsedown, which does not support all of GitHub's features. For example, specifying the language of code listings is not supported.