March 21, 2020 Can I get the compiler to warn or fail on uninitialized variables/class members? | ||||
---|---|---|---|---|
| ||||
Hello, everyone I would say that disallowing uninitialized variables is a great way increase correctness in a program. Still, I can't seem to find a way to force my members/variables to always be initialized. See, for example: class Enemy{ int strength; int health; this(int strength){ /*oops, forgot to ask for health*/) this.strength = strength; } } void main(){ Enemy enemy1; //enemy1 is null, which is asking for a segfault/null pointer exception auto enemy2 = new Enemy(123); //enemy2 starts with health == 0 } Am I missing something here? Or is there no way to have initialization be guaranteed by the compiler? I know that uninitialized variables will be set to their respective .init, but that doesn't help me at all when I add something to a class and forget to put initialization code into the constructor. Thank you, Tomaz |
Copyright © 1999-2021 by the D Language Foundation