Bug 1619 – "Missing initializer for const field" only reported if an explicit constructor is present
Status
RESOLVED
Resolution
WONTFIX
Severity
normal
Priority
P2
Component
dmd
Product
D
Version
D1 (retired)
Platform
x86
OS
Windows
Creation time
2007-10-27T16:55:27Z
Last change time
2019-07-16T04:08:01Z
Keywords
accepts-invalid
Assigned to
No Owner
Creator
Ary Borenszweig
Comments
Comment #0 by ary — 2007-10-27T16:55:27Z
The following code gives a compiler error:
---
class X {
const int x;
this() { }
}
---
main.d(3): constructor main.X.this missing initializer for const field x
But this one:
---
class X {
const int x;
}
---
compiles correctly. Since the semantic of both files is the same, an error should also be reported in the second case.
Comment #1 by andrej.mitrovich — 2013-01-23T11:08:02Z
I don't know whether this is a valid report. The same behavior is in D2, afaik the field will be initialized with .init, whereas if you introduce a constructor the compiler expects you to initialize it yourself.
Can anyone with more insight confirm?
Comment #2 by maxim — 2013-01-24T07:24:35Z
(In reply to comment #1)
> I don't know whether this is a valid report. The same behavior is in D2, afaik
> the field will be initialized with .init, whereas if you introduce a
> constructor the compiler expects you to initialize it yourself.
>
> Can anyone with more insight confirm?
In both cases i is initialized to 0.
import std.stdio;
class A
{
const int i;
}
class B
{
const int i;
this() { writeln(i); i = 2; }
}
void main()
{
A a = new A;
B b = new B;
}
As I understand the point of the requirement is that after exiting from ctor, const member cannot be altered (this assumption can be invalidated). So, the only opportunity to make const member store useful runtime value is during constructor invocation. This ability cannot be replaced by enum or manifest constant because they are shared across all instances. So, the only opportunity to configure at rt a const member which can be different across instances is a ctor (this assumption can be broken).
However, loosing this opportunity is not an error : if a user forgot to set up a const member, he can easily go back and modify it. Also a const member is still initialized, so no invalid value is created.
When this feature was added it likely had a rationale, but I don't see why not initializing a const member is treated so severely as an error.
Comment #3 by pro.mathias.lang — 2019-07-16T04:08:01Z