Struct Constructors
Adam D. Ruppe via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Jun 16 15:20:14 PDT 2014
On Monday, 16 June 2014 at 22:03:28 UTC, Mark Blume wrote:
> Why exactly isn't a constructor without any parameters is not
> allowed?
The idea is that declaring a plain struct always has almost zero
cost - it is just static data with no extra code run. A zero-arg
constructor (aka a default constructor in C++) that is run
automatically on the declaration breaks that idea.
Since sometimes people want it anyway the compromise is to make a
static opCall and explictly use it with parenthesis. This was
introduced before D had any struct constructors at all.
Then struct constructors were added to D later and they override
the old static opCall method... but they must have at least one
parameter.
So short answer is the confusion is caused by two historical
features that basically did the same thing. Nowadays, static
opCall should mostly be avoided. Use constructors instead. Only
if you need a zero arg constructor should you consider static
opCall.
> Does "Struct(params)" also call "Struct.opCall(params)?"
If there's no constructor, i think it can. But like i said above,
you should avoid this because it is mostly just historical
baggage. Use constructors.
BTW non-static opCall is a different story, that can be useful
for defining functor objects. That only works on an instance
object though:
struct Foo { void opCall() { } }
Foo foo; // doesn't call any code, just plain variable declaration
foo(); // calls foo.opCall();
More information about the Digitalmars-d-learn
mailing list