Construct immutable member in derived class
Timoses
timosesu at gmail.com
Wed Apr 4 21:46:13 UTC 2018
On Wednesday, 4 April 2018 at 18:11:12 UTC, Jonathan M Davis
wrote:
> On Wednesday, April 04, 2018 16:05:52 Timoses via
>>
>> ```
>> 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
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?
More information about the Digitalmars-d-learn
mailing list