Immutable objects and constructor ?

chmike via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri May 20 09:09:54 PDT 2016


I solved the problem by moving the class Obj definition out of 
the class MyInfo.
I still don't understand why I had to do that. In C++ this would 
work without problem.

I now have

interface Info {. . .}

class Obj : Info {. . .}

class MyInfos
{
     . . .
     static immutable Obj one = new immutable Obj(...);
     static immutable Obj two = new immutable Obj(...);
     . . .
}

This now compiles without a peep.

But I now met another error in my main(). I can't assign the 
immutable object to a mutable reference.

Info x1 = MyInfos.one;

Is it possible to define a mutable reference to an immutable 
instance ? 

This is confusing and frustrating. In C++ we can write
MyInfos {
    . . .
    // one is a constant pointer to a constant object of type Obj
    Obj const * const one;
    . . .
}

And in main()

Info const * x1 = MyInfos.one;

x1 i a modifiable pointer to a constant object of type Info.

Is this possible in D ? I couldn't find how to do that.




More information about the Digitalmars-d-learn mailing list