Initializing a class member that is an object

Laurent Tréguier laurent.treguier.sink at gmail.com
Fri Mar 30 10:54:16 UTC 2018


Coming from a more Java-esque background, I'm used to sometimes 
initializing class members outside of the constructor :

class MyClass {
     Object member = new Object();
}

I've tried using this in D, but I've come to realize it acts very 
differently. In Java, the `new Object()` will be executed every 
time a new `MyClass` object is instantiated. In D however, it 
seems to be executed once, and members of every `MyClass` object 
will then be initialized with a reference to that one unique 
`Object`.

Example: https://run.dlang.io/is/Qlx2xY

Is this behavior really intentional ? I don't really see how it 
could be useful, and it's really confusing at first to see new 
objects with weird values even if none of their members has been 
touched yet...


More information about the Digitalmars-d-learn mailing list