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

chmike via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon May 23 00:03:08 PDT 2016


On Saturday, 21 May 2016 at 17:32:47 UTC, dan wrote:

> (This effect could be simulated by making my_var into a 
> function, but i don't want to do that.)

May I ask why you don't want to do that ?

In D you can call a function without args without ().

So if you write

private int my_var_ = 4; // where 4 is the default initialization 
value
@property int my_var1() { return my_var_; }
final int my_var2() { return my_var_; }
int my_var3() { return my_var_; }

int x = obj.my_var1;
x = obj.my_var2;
x = obj.my_var3;


my_var3 is virtual so I guess you get the overhead of a virtual 
method call which is probably not what you want.

my_var2 can't be overriden and if it doesn't itself override a 
method with a same name in a base class the compiler may optimize 
its call by inlining it. It's like a static method with 'this' 
passed as argument.

I'm not fully sure about my_var1. I'm still a beginner, but I 
think the compiler will optimize it into inlined instruction if 
it can as for my_var2.

Making the user accessing the member variables directly may look 
like it's more efficient, but it's bad API design because you 
can't change the class implementation affecting my_var_ without 
breaking the API. The D way enforces good programming and API 
design and optimizes as much as possible.



More information about the Digitalmars-d-learn mailing list