D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 3944 - Require immutable annotation for new fields of class inherited from immutable class
Summary: Require immutable annotation for new fields of class inherited from immutable...
Status: NEW
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P4 enhancement
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2010-03-12 14:57 UTC by bearophile_hugs
Modified: 2024-12-13 17:51 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description bearophile_hugs 2010-03-12 14:57:54 UTC
This is a wrong D2 program:


immutable class Foo {}
class Bar : Foo { int x; }
void main() {
    auto b = new Bar;
    b.x = 10; // line 5
}


From the error message it's clear that x is not a mutable variable:
test.d(5): Error: can only initialize const member x inside constructor

But from the code of the Foo class there is no clear indication that x is immutable. So in this situation I think it's better if the compiler requires a immutable annotation on x too, for code readability, something like:


immutable class Foo {}
class Bar : Foo { int x; } // Error: attribute x requires 'immutable' annotation
void main() {
    auto b = new Bar;
}



immutable class Foo {}
class Bar : Foo { immutable int x; } // OK, no error
void main() {
    auto b = new Bar;
}
Comment 1 zhyhbvawwj 2010-07-07 14:36:34 UTC
Here's another situation that produces the same error message:

class Foo
{
 int x;
 immutable void bar() { x = 1; }
}

Error: can only initialize const member x inside constructor

It should probably report something along the lines of "immutable member function cannot modify member variables".
Comment 2 dlangBugzillaToGithub 2024-12-13 17:51:36 UTC
THIS ISSUE HAS BEEN MOVED TO GITHUB

https://github.com/dlang/dmd/issues/18176

DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB