Construct immutable member in derived class

Simen Kjærås simen.kjaras at gmail.com
Wed Apr 4 10:41:52 UTC 2018


On Wednesday, 4 April 2018 at 10:11:37 UTC, Timoses wrote:
> Example:
>
> ```
> class A
> {
>     immutable int i;
>
>     this(){}
> }
>
> class B : A
> {
>     this()
>     {
>      	this.i = 3;
>     }
> }
>
> void main()
> {
>     auto b = new B;
> }
> ```
>
> throws:
>> Error: constructor `onlineapp.A.this` missing initializer for 
>> immutable field i
>> Error: cannot modify immutable expression this.i
>
> Why can't I initialize the immutable member in the derived 
> class?

Because by the time B's constructor is called, A might already 
have initialized it, and rely on it never changing. The solution 
is to add a constructor overload to A, and call that from B:

class A
{
     immutable int i;

     protected this(int i) {
         this.i = i;
     }
}

class B : A
{
     this()
     {
         super(3);
     }
}

unittest
{
     auto b = new B;
}

--
   Simen


More information about the Digitalmars-d-learn mailing list