Construct immutable member in derived class

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed Apr 4 18:11:12 UTC 2018


On Wednesday, April 04, 2018 16:05:52 Timoses via Digitalmars-d-learn wrote:
> 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;
> }
> ```

That code doesn't compile - at least not with dmd master. It gives these two
errors:

q.d(5): Error: constructor `q.A.this` missing initializer for immutable 
field i
q.d(12): Error: cannot modify immutable expression this.i

So, it's an error that the base class doesn't initialize the immutable
member, and it's an error for the derived class to try to assign to it.

- Jonathan M Davis




More information about the Digitalmars-d-learn mailing list