Can I get the compiler to warn or fail on uninitialized variables/class members?

Tomaz tom.fogaca at gmail.com
Sat Mar 21 16:45:18 UTC 2020


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


More information about the Digitalmars-d-learn mailing list