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
Sat May 21 11:19:31 PDT 2016


On Saturday, 21 May 2016 at 17:32:47 UTC, dan wrote:
> Is it possible to have a class which has a variable which can 
> be seen from the outside, but which can only be modified from 
> the inside?
>
> Something like:
>
> class C {
>   int my_var = 3;     // semi_const??
>   void do_something() { my_var = 4; }
> }
>
> And then in another file
>
> auto c = new C();
> c.my_var = 5; // <<<- should trigger a compile-time error
> writeln("the value is ", c.my_var);  // <<<- should print 3
> c.do_something();
> writeln("the value is ", c.my_var);  // <<<- should print 4
>
> Reading Alexandrescu's book suggests the answer is "no" (the 
> only relevant type qualifiers are private, package, protected, 
> public, and export, and none seem appropriate).
>
> (This effect could be simulated by making my_var into a 
> function, but i don't want to do that.)
>
> TIA for any info!
>
> dan

You can create a const accessor for the variable. Then you can 
have it be mutable internally but const externally.

Class C
{
     int _my_var = 2;

     void setMyVarTo3() { _my_var = 3; }

     @property const(int) my_var() { return _my_var; }
}

auto c = new C();
writeln(c.my_var); //Prints 2
c.setMyVarTo3();
writeln(c.my_var); //Prints 3
c.my_var = 4; //Error, cannot modify const(int)


More information about the Digitalmars-d-learn mailing list