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

2020-03-21 Thread Kagamin via Digitalmars-d-learn

Maybe if you teach dparse to do this check.


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

2020-03-21 Thread Tomaz via Digitalmars-d-learn

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