What is the difference between initializing instance variables in & from the constructor?

The following code example is milkinitialized by the constructor, but eggnot. milk.spill()not segfault but egg.crack()does. What is the difference between the two ways to initialize an instance variable? Why is the former correct while the latter invokes segfaults?

import std.stdio;

void main() {
  auto k = new Kitchen();
  k.pollute();
}

class Kitchen {
  Milk milk;
  Egg egg = new Egg();

  this() {
    milk = new Milk();
  }

  void pollute() {
    writeln("spilling milk");
    milk.spill();
    writeln("cracking egg");
    egg.crack();
  }
}

class Milk {
  bool spilt = false;
  void spill() { spilt = true; }
}

class Egg {
  bool cracked = false;
  void crack() { cracked = true; }
}
+4
source share
1 answer

So the difference between the two methods is when the code is executed. When you initialize in the constructor, the code runs at runtime, when each new object is created. When you do this directly on a class member, the object is actually created at compile time and is statically referenced.

, Kitchen Milk. new Kitchen, , new Milk.

Egg . , - . , new Kitchen s Egg. , new Egg new Kitchen, , , , .

, new Egg , , , - , new Kitchen, !

+5

Source: https://habr.com/ru/post/1615605/


All Articles