class variable initialization

NonNull non-null at use.startmail.com
Sat Apr 15 15:03:39 UTC 2023


On Saturday, 15 April 2023 at 14:17:19 UTC, Vijay Nayar wrote:
> 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);
> }
> ```

I should have made it clear that want a single shared default 
object. Your code above solves that problem. So does

```
Var defaultObj;
static this() { defaultObj = new Var(); }
```

By wrapping the new variable and the constructor call to 
initialize it in MyClass, you eliminate the need to call the 
constructor, which is what I want, but now you add the need to 
call another constructor. So for my purposes this is just moving 
the problem of null to another place.



More information about the Digitalmars-d-learn mailing list