+ 6

Why this is happening

class A{int a;} main(){ A b=new A(); b.a++; } //no errors but when I do that main(){ int x; x++; //error } maybe because of the type of variable the first is global and the second is local

14th Sep 2018, 10:16 PM
ABADA S
ABADA S - avatar
2 Réponses
+ 2
In the second one you haven't initialized the local variable, so you can't do any operations on it. In the first one, class level variables are initialized to their default values when you create a new object, so the int in the class A initializes to 0
15th Sep 2018, 1:48 AM
Dan Walker
Dan Walker - avatar
15th Sep 2018, 1:48 AM
Hatsy Rei
Hatsy Rei - avatar