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

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue May 24 07:10:16 PDT 2016


On 5/21/16 1:32 PM, 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!

A while ago, I discovered that this works.

class C {
    union
    {
       private int _my_var;
       public const int my_var;
    }
    void do_something() { _my_var = 4; }
}

-Steve


More information about the Digitalmars-d-learn mailing list