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

Mike Parker via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat May 21 20:06:44 PDT 2016


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.


More information about the Digitalmars-d-learn mailing list