Programming in D page 295 - disable default constructor
Brother Bill
brotherbill at mail.com
Tue Feb 10 12:04:05 UTC 2026
When adding an explicit constructor such as ```this(string
fileName)```, this is "supposed" to remove the "default"
constructor. Then the developer needs to add back the default
constructor.
But in this example, variable ```a4``` constructs just fine, and
one can't add a default constructor, which is commented out.
There is a way to force the issue, by adding ```@disable
this();```, but that seems like brute force.
Why does the default parameterless constructor still exist after
creating an explicit constructor ```this(string fileName)```?
Does this have something to do with the difference between
structs and classes?
That is, that structs "always" have a default parameterless
constructor, unless ```@disable(this);``` is added.
source/app.d -- It compiles and runs.
```
void main() {
auto a1 = Archive("records");
// auto a2 = Archive("");
// auto a3 = Archive(null);
auto a4 = Archive();
}
struct Archive {
string fileName;
// @disable this(); // Disable the default constructor
// This won't compile
// this()
// {
// this.fileName = "default_file_name";
// }
this(string fileName)
in (fileName.length > 0)
{
this.fileName = fileName;
}
}
```
More information about the Digitalmars-d-learn
mailing list