Is there a way to make a class variable visible but constant to outsiders, but changeable (mutable) to the class itself?

Meta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun May 22 12:29:59 PDT 2016


On Sunday, 22 May 2016 at 03:06:44 UTC, Mike Parker wrote:
> On Saturday, 21 May 2016 at 19:17:00 UTC, dan wrote:
>> Thanks Vit, Meta, and Yuxuan for your speedy help!
>>
>> So 3 pieces to put together, function, const, and @property 
>> (and i guess final for protection against subclasses).
>
> Minimally, there are two pieces to this: a private member 
> variable and a function.
>
> class Foo {
>   private int _myVar;
>   int myVar() { return _myVar; }
> }
>
> The private is necessary because class members in D are all 
> public by default. If it isn't there, then _myVar can be 
> directly modified outside of the module. Be aware, though (if 
> you aren't already), that private members *are* accessible 
> outside of the class in the same module, e.g.:
>
> module foo;
>
> class Foo {
>   private int _myVar;
>   int myVar() { return _myVar; }
> }
>
> void printMyVar() {
>     import std.stdio : writeln;
>     auto f = new Foo;
>     writeln(f);
> }
>
> As for 'const' and '@property', neither is strictly a 
> requirement to implement this idiom. Adding const means that 
> you can call the function through const references, but if 
> that's not something you want to allow for some reason, then 
> don't add it.
>
> @property right now doesn't really do anything other than allow 
> for self-documenting code. Perhaps one day it will be fully 
> implemented and require callers to drop the parentheses in 
> calls to @property functions, but for now it doesn't do that. 
> Use it as much as you want, but just understand it isn't 
> necessary for the functionality you are after.

Const *is* necessary to prevent _myVar being written to through 
code like:

f.myVar = 4;

Of course this isn't necessary for value types, but for reference 
types.

It's also useful for value types, IMO, for preventing someone 
from doing this:

f.myVar = 4;

And wondering why the code has no effect.


More information about the Digitalmars-d-learn mailing list