Immutable objects and constructor ?

Marc Schütz via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri May 20 08:43:28 PDT 2016


On Friday, 20 May 2016 at 15:07:53 UTC, chmike wrote:
> The error message is gone, but I now have another compilation 
> error message I don't understand.
>
> This is what I have in fact
>
> interface Info { . . . }
>
> class MyInfos {
>    . . .
> protected:
>    class Obj : Info
>    {
>        . . .
>    }
>
> public:
>    static immutable Obj one = new immutable Obj(...);
>    static immutable Obj two = new immutable Obj(...);
> }
>
> I get a compiler error in the two assignments to the static Obj 
> member variables:
> 'this' is only defined in non-static member functions, not 
> MyInfos
>
> Is it related to the fact that the Obj class is encapsulated ?

Yes, nested classes have an implicit reference to their parent 
object, which doesn't exist in your case.

>
>
> My goal is to be able to write things like this:
>
> void main() {
>    Info x1 = MyInfos.one, x2 = MyInfo.two, x3;
>    assert(x3 is null);
>    x3 = x1;
>    assert(x3 is x1);
>    assert(x3 is MyInfo.one);
>
>    // Use static immutable instance references as case arg in 
> switch
>    switch(x1) {
>    case MyInfo.one: ...;
>    }
> }

It looks like your don't actually need `Obj` to be a real nested 
class. Try declaring it as `static Obj : Info { }`. This should 
work if `Obj`'s methods don't need access to `MyInfo`'s 
non-static members.


More information about the Digitalmars-d-learn mailing list