Can static variables in methods be local for each object?
cc
cc at nevernet.com
Fri Jul 23 05:16:23 UTC 2021
On Tuesday, 20 July 2021 at 09:24:07 UTC, Mark Lagodych wrote:
> Is there a way to make myvar local to each instance of `X`
> without making it a variable of `X`? Just curious.
Sorry if I missed something obvious but is there a specific
reason why it isn't just a class member variable?
```d
class X {
int myvar = 1234;
int x(int param) {
if (param == 0) return myvar;
else { myvar = param; return myvar; }
}
}
```
??
Why would you need a static variable inside a method but also
have that static variable unique to each class instance, but not
stored inside the class? I could see maybe if the class
definition were private and you can't change it, in which case
you could extend it:
```d
class X {
// Someone else's module
}
class MyX : X {
int myvar = 1234;
int x(int param) {
return param ? myvar = param : myvar;
}
}
void main() {
auto x1 = new MyX();
auto x2 = new MyX();
x1.x(0).writeln;
x2.x(0).writeln;
x1.x(17).writeln;
x2.x(0).writeln;
}
```
More information about the Digitalmars-d-learn
mailing list