Construct immutable member in derived class

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed Apr 4 22:47:07 UTC 2018


On Wednesday, April 04, 2018 21:46:13 Timoses via Digitalmars-d-learn wrote:
> On Wednesday, 4 April 2018 at 18:11:12 UTC, Jonathan M Davis
> > 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.
>
> I know, should have mentioned it. The question is why, however?
> A rule like the above would force all derived classes to
> initialize the immutable variable from the base class (if they
> were allowed to).
> Why aren't they?

Because doing that basically makes it impossible to guarantee that the type
system isn't violated. Once an immutable variable has been initialized, its
value must _never_ change. It must be initalized exactly once, and the
compiler doesn't necessarily have any clue what the base class constructors
did or didn't do. There's no guarantee that it even has access to the
function bodies for the base class when compiling the derived class. So,
there is no way for it to safely put off the initialization of any base
class members for the derived class to do.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list