www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Can I get the compiler to warn or fail on uninitialized

reply Tomaz <tom.fogaca gmail.com> writes:
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
Mar 21 2020
parent Kagamin <spam here.lot> writes:
Maybe if you teach dparse to do this check.
Mar 21 2020