Do classes require explicit constructors?
Steven Schveighoffer
schveiguy at gmail.com
Sun Feb 15 00:35:20 UTC 2026
On Saturday, 14 February 2026 at 15:42:15 UTC, Brother Bill wrote:
> Is this expected behavior, that is, we always need to create
> our constructors, no free constructor is built for us by the D
> compiler?
If you don't define a constructor, a default no-argument
constructor is provided for you. If you want a constructor with
parameters, you have to define it.
```d
class C {
int i;
}
struct S {
int i;
}
void main() {
auto c = new C(); //ok
auto s = new S(); //ok
auto s2 = new S(1); //ok, default ctor takes optional
parameters for fields
auto c2 = new C(1); //error
}
```
> If so, this is a clear departure from C# and Eiffel, where one
> gets a free constructor if no explicitly declared constructors.
C# also provides the same mechanism as D, a default ctor with no
args.
-Steve
More information about the Digitalmars-d-learn
mailing list