D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 7211 - Initializing const members in derived classes' constructors
Summary: Initializing const members in derived classes' constructors
Status: RESOLVED FIXED
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P3 normal
Assignee: No Owner
URL:
Keywords: rejects-valid
Depends on:
Blocks:
 
Reported: 2012-01-03 11:39 UTC by Vladimir Panteleev
Modified: 2018-04-05 15:14 UTC (History)
2 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Vladimir Panteleev 2012-01-03 11:39:16 UTC
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 Maksim Zholudev 2016-03-28 14:05:48 UTC
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 RazvanN 2018-04-05 15:14:12 UTC
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.