On Saturday, 15 April 2023 at 14:05:17 UTC, NonNull wrote:
I want a way to default initialize a class variable to a default object (e.g. by wrapping it in a struct, because initialization to null cannot be changed directly). Such a default object is of course not available at compile time which seems to make this impossible. Can this be done in some way?

Assuming you want a default object that is unique per class instance rather than shared among all instances of the same class, then I think the constructor might be where you want to initialize such a member.

E.g.
```
class Var {
  int val;
  this(int val) {
    this.val = val;
  }
}

class MyClass {
  Var var;

  this() {
    var = new Var(3);
  }
}
```

I believe if you do initialization at the class declaration level, then every instance of the class shares the same instance, e.g.:

```
class Var {}

class MyClass {
  Var var = new Var();
}

void main() {
  MyClass c1 = new MyClass();
  MyClass c2 = new MyClass();
  assert(c1.var is c2.var);
}
```

Reply via email to