Struct no-arg constructor?

monarch_dodra monarchdodra at gmail.com
Wed Jul 25 03:30:56 PDT 2012


On Wednesday, 25 July 2012 at 09:51:49 UTC, Jonathan M Davis 
wrote:
> If you want to be able to do S(), then declare a static opCall 
> for S which
> returns an S constructed in the way that you want.
>
> struct S
> {
>     static S opCall()
>     {
>         //do whatever you do
>         return s;
>     }
> }
>
> auto s = S();
>
> but
>
> S s;
>
> will always be init. But you can't have a default constructor, 
> because then it
> conflicts with what init would be doing. e.g. would
>
> S s;
> [SNIP]

This makes *so* much sense now. I couldn't understand the point 
of "S a = S();" up until now. Thanks a lot.

I read TDPL back to back like 5 times before posting this, but it 
never mentions opCall. I just checked the index right now, it is 
not in there. Is this new?

Provided the existence of "opCall", though why would I keep 
writing constructors?

Also, while I understand why we can't have a "default" 
constructor, your explanations perfectly proves we *can* have a 
"no-arg" (subtle difference) one:
S s = S(); //Initialize s to this();
S s;       //Leave s as S.init

It seems like opCall is a bypass to a language restriction...


More information about the Digitalmars-d mailing list