Skip to content

Commit f03f172

Browse files
authored
[spec/class] Inside non-static method, member vars are in scope (#4258)
Add example. Also change to 'class instance members' as methods are in scope too.
1 parent efbdafa commit f03f172

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

spec/class.dd

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -253,11 +253,30 @@ $(H3 $(LNAME2 field_properties, Field Properties))
253253

254254
$(H2 $(LNAME2 member-functions, Member Functions (a.k.a. Methods)))
255255

256-
$(P Non-static member functions have an extra hidden parameter
256+
$(P Non-static member functions must be called on an instance of their class.
257+
They have an extra hidden parameter
257258
called $(DDSUBLINK spec/expression, this, `this`) through which the class object's other members
258259
can be accessed.
260+
Inside the function body, the class instance members are in scope.
259261
)
260262

263+
$(SPEC_RUNNABLE_EXAMPLE_RUN
264+
---
265+
class C
266+
{
267+
int a;
268+
269+
void foo()
270+
{
271+
a = 3; // assign to `this.a`
272+
}
273+
}
274+
275+
auto c = new C;
276+
c.foo();
277+
assert(c.a == 3);
278+
---
279+
)
261280
$(P Non-static member functions can have, in addition to the usual
262281
$(GLINK2 function, FunctionAttribute)s, the attributes
263282
$(D const), $(D immutable), $(D shared), $(D inout), $(D scope) or $(D return scope).
@@ -268,6 +287,7 @@ $(SPEC_RUNNABLE_EXAMPLE_FAIL
268287
class C
269288
{
270289
int a;
290+
271291
void foo() const
272292
{
273293
a = 3; // error, 'this' is const

spec/expression.dd

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2084,7 +2084,8 @@ $(TROW `(` *Expression* `)`, Evaluate an expression - useful as a
20842084

20852085
$(H3 $(LNAME2 this, this))
20862086

2087-
$(P Within a constructor or non-static member function, $(D this) resolves to
2087+
$(P Within a constructor or $(DDSUBLINK spec/class, member-functions,
2088+
non-static member function), $(D this) resolves to
20882089
a reference to the object for which the function was called.
20892090
)
20902091
$(P $(DDSUBLINK spec/type, typeof-this, `typeof(this)`) is valid anywhere

0 commit comments

Comments
 (0)