On Sunday, 20 March 2016 at 02:21:51 UTC, Mike Parker wrote:
On Saturday, 19 March 2016 at 20:24:15 UTC, szymski wrote:

class A {
        B b = new B();  
}

This is *default* initialization, not per instance initialization. The compiler will create one instance of B and it will become the default initializer of b in *every* instance of A. You can verify that with this:

class B {}
class A {
    B b = new B;
}
void main() {
    auto as = [new A, new A, new A];
    assert(as[0].b is as[1].b);
    assert(as[1].b is as[2].b);
    assert(as[0].b is as[2].b);
}

Here, all of the asserts will pass. But add a constructor to A that does this:

this() { b = new B; }

And now the first assert will fail. This is *per-instance* initialization.

Ok, I understand now, thanks. I used C# a lot before and there default initialization worked like per instance initialization.

Reply via email to