www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Default value for member class

reply JN <666total wp.pl> writes:
class IntValue
{
     int x = 5;
}

class Foo
{
     IntValue val = new IntValue();
}

void main()
{
     Foo f1 = new Foo();
     Foo f2 = new Foo();

     assert(f1.val == f2.val);
}


Is this expected? Or should each Foo have their own IntValue 
object? They're equal right now, changing one changes the other. 
When exactly is the "new IntValue" happening? On program init, or 
when calling new Foo() for the first time?
Feb 10 2020
next sibling parent Adam D. Ruppe <destructionator gmail.com> writes:
On Monday, 10 February 2020 at 18:18:16 UTC, JN wrote:
 Is this expected?
Yes, it is per the spec, though new users find it weird. Maybe we should change this but any static initializer is run at CTFE. Then the *static pointer* is put into the static initializer, which is just copied over before the constructor. So it ends up being an instance reference to a static object. If you want a new one, call `new Foo` in a regular constructor.
Feb 10 2020
prev sibling parent Steven Schveighoffer <schveiguy gmail.com> writes:
On 2/10/20 1:18 PM, JN wrote:
 class IntValue
 {
      int x = 5;
 }
 
 class Foo
 {
      IntValue val = new IntValue();
 }
 
 void main()
 {
      Foo f1 = new Foo();
      Foo f2 = new Foo();
 
      assert(f1.val == f2.val);
 }
 
 
 Is this expected?
Define "expected" ;) It's been this way for a while actually. It's the way it's currently implemented, but I wouldn't say that anyone really expects this. The end result is you just shouldn't create default values for object members.
 Or should each Foo have their own IntValue object? 
That would be ideal.
 They're equal right now, changing one changes the other. When exactly is 
 the "new IntValue" happening? On program init, or when calling new Foo() 
 for the first time?
The new IntValue is happening at compile-time and stuck in the static data segment. Then every new instance of Foo gets a pointer to that one instance. -Steve
Feb 10 2020