why does a constructor with default arguments fail to match, when default construction is disabled?
Nick Treleaven
nick at geany.org
Sat Aug 22 09:28:02 UTC 2026
On Saturday, 22 August 2026 at 04:19:54 UTC, DanielG wrote:
> This is actually a reduced example - I first noticed the
> problem when my class contained a struct with `@disable this`.
...
> 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.
There's no need to `@disable this();` for a class with a defined
constructor, as one would not be generated:
https://dlang.org/spec/class.html#implicit-base-construction
There seems to be a bug with default constructor arguments here,
however you can workaround it by using a delegating constructor:
```d
import std.stdio;
struct S
{
int i;
@disable this();
}
class MyClass {
S s;
//this(string y = "hi") { // bug
// workaround:
this() { this("hi"); }
this(string y) {
writeln("hello from MyClass constructor");
S tmp = {1};
s = tmp;
}
}
void main()
{
// always works
auto x = new MyClass("hi");
// works now
auto y = new MyClass;
}
```
More information about the Digitalmars-d-learn
mailing list