Bug 7211 – Initializing const members in derived classes' constructors
Status
RESOLVED
Resolution
FIXED
Severity
normal
Priority
P3
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2012-01-03T11:39:16Z
Last change time
2018-04-05T15:14:12Z
Keywords
rejects-valid
Assigned to
No Owner
Creator
Vladimir Panteleev
Comments
Comment #0 by dlang-bugzilla — 2012-01-03T11:39:16Z
I believe this code is valid:
class C
{
immutable int x;
}
class D : C
{
this()
{
x = 42;
}
}
Compiler complains:
test.d(10): Error: can only initialize const member x inside constructor
Even if this code is invalid, the error message is misleading in this case.
Comment #1 by maximzms — 2016-03-28T14:05:48Z
The error message has been changed.
DMD 2.070.2:
test.d(10): Error: cannot modify immutable expression this.x
This is valid behavior if qualified members of classes are supposed to be dealt as described here:
https://issues.dlang.org/show_bug.cgi?id=9665#c9
I wonder whether this is documented somewhere else.
Comment #2 by razvan.nitu1305 — 2018-04-05T15:14:12Z
As Maksim said, the error has changed to "test.d(10): Error: cannot modify immutable expression this.x". This is the correct behavior since x is constructed in the implicit super call to C. When D's constructor tries to modify it, it is already cooked and cannot be modified. Closing as fixed.