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
Sun May 22 20:22:35 PDT 2016
On Sunday, 22 May 2016 at 19:29:59 UTC, Meta wrote:
> 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.
>
I was referring specifically to marking the function const, not
the return type. Marking the return type const is highly
context-dependent. It's perfectly reasonable to return a
non-const class reference from a getter property. As long as the
internal reference is private, it isn't going to be overwritten
externally without a setter property. I don't see how it could be
considered necessary. For a pointer, sure, to prevent
*(bar.fooVer) = Foo(10). But for class references it's only
necessary if you don't want the returned instances members to be
modified.
> 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.
The compiler already gives an error message describing the
problem:
Error: function mod.Foo.myVar () is not callable using argument
types (int)
How does const help here?
More information about the Digitalmars-d-learn
mailing list