Construct immutable member in derived class

Timoses timosesu at gmail.com
Wed Apr 4 16:05:52 UTC 2018


On Wednesday, 4 April 2018 at 10:41:52 UTC, Simen Kjærås wrote:
> Because by the time B's constructor is called, A might already 
> have initialized it, and rely on it never changing.
What about:

```
class A
{
     immutable int i;

     this(){}
}

class B : A
{
     this()
     {
      	this.i = 3;
         super();              // <- specifically calling
                               //    super constructor afterwards
     }
}

void main()
{
	auto b = new B;
}
```

Same result

> 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

This becomes a bit hideous, unfortunately, when there are many 
initializations involved.

Found this, but it doesn't mention anything about derived 
classes..
https://dlang.org/spec/class.html#field-init


More information about the Digitalmars-d-learn mailing list