why does a constructor with default arguments fail to match, when default construction is disabled?
DanielG
simpletangent at gmail.com
Sat Aug 22 04:19:54 UTC 2026
This is actually a reduced example - I first noticed the problem
when my class contained a struct with `@disable this`. But it
seems to be the same mechanism responsible for what's going on
below:
```
import std.stdio;
class MyClass {
// this prevents `new MyClass()` from matching the default arg
constructor (which it does normally). why?
@disable this();
this(string y = "hi") {
writeln("hello from MyClass constructor");
// output appears in all cases, so we know this ctor is
matching even when this() exists
// (unless @disable this() exists above, which is causing this
ctor to fail to match / compilation failure)
}
}
void main()
{
auto x = new MyClass("hi"); // OK in all cases
auto y = new MyClass(); // Error: constructor
`app.MyClass.this` cannot be used because it is annotated with
`@disable`
// ... but in the absence of
@disable this(), our desired constructor IS matching,
// not the default constructor.
}
```
I would expect the human-provided constructor with default
arguments to be matched even in the absence of a default/zero-arg
constructor. From the output we can see that the provided
constructor is the only one that ever matches/runs ... but if we
`@disable this`, suddenly it refuses to match. This is surprising.
More information about the Digitalmars-d-learn
mailing list