Skip to content

Commit e42c209

Browse files
authored
[spec/class] Improve constructor docs (#4256)
* [spec/class] Improve constructor docs Describe a constructor. Change example not to need `this.i` to show member variable is in scope. `return;` can be used. * Show `this.i = i;` constructor pattern, add nullary ctor
1 parent f03f172 commit e42c209

File tree

1 file changed

+18
-3
lines changed

1 file changed

+18
-3
lines changed

spec/class.dd

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -450,22 +450,31 @@ $(H2 $(LNAME2 class-instantiation, Class Instantiation))
450450

451451
$(H3 $(LNAME2 constructors, Constructors))
452452

453+
$(P A constructor is a special $(RELATIVE_LINK2 member-functions, member function)
454+
which is normally $(RELATIVE_LINK2 instantiation-process, invoked by the compiler)
455+
when the class instance is created.)
456+
453457
$(GRAMMAR
454458
$(GNAME Constructor):
455459
$(D this) $(GLINK2 function, Parameters) $(GLINK2 function, MemberFunctionAttributes)$(OPT) $(GLINK2 function, FunctionBody)
456460
$(D this) $(GLINK2 function, Parameters) $(GLINK2 function, MemberFunctionAttributes)$(OPT) $(GLINK2 function, MissingFunctionBody)
457461
$(GLINK2 template, ConstructorTemplate)
458462
)
459463

460-
$(P Constructors are defined with a function name of $(D this)
461-
and have no return value:)
464+
$(P A constructor is declared with a function name of $(D this)
465+
and no return type:)
462466

463467
$(SPEC_RUNNABLE_EXAMPLE_RUN
464468
------
465469
class A
466470
{
467471
int i;
468472

473+
this() // constructor taking no arguments
474+
{
475+
i = 2; // initialize `this.i`
476+
}
477+
469478
this(int i) // constructor taking an int argument
470479
{
471480
this.i = i; // initialize field `i` from parameter `i`
@@ -474,11 +483,17 @@ $(GNAME Constructor):
474483

475484
void main()
476485
{
477-
A a = new A(3);
486+
A a = new A; // instantiate A and call `A.this()`
487+
assert(a.i == 2);
488+
489+
a = new A(3); // instantiate A and call `A.this(3)`
478490
assert(a.i == 3);
479491
}
480492
------
481493
)
494+
$(P Explicitly returning a value in a constructor is not allowed,
495+
however `return;` may be used to exit the function early.)
496+
482497

483498
$(H3 $(LNAME2 base-construction, Base Class Construction))
484499

0 commit comments

Comments
 (0)