+ 2
Manav Roy No. It does not become static. It is just like a variable that you declare inside main(). You can refer to it from inside main() and it will get deleted when the main() function is over. I think it would help knowing the difference between static and non-static variables, in case you're confused. "static" implies that the variable will stay alive for the whole duration of the "program" and will refer to the same location in memory no matter how many times the function/class it was defined in is called/initialized. This is the case with the 'count' MyClass member in your 1st code OTOH, a "non-static" variable will stay alive as long as the function it was defined in is being executed. As soon as the function is over, its stack will be cleared and the variable will get deleted, which happens to the 'count' variable in your second code
6th Jun 2022, 3:40 PM
XXX
XXX - avatar
+ 2
When you declare a static member in a class it does not belong to any instance of that class, it belongs to the type of the class. So the static member does not have any visibility on whats is inside the class until you pass a contructed instance to it. A static member function can only access a static member of the class. A non-static member function can access either a static or non-static member of the class.
6th Jun 2022, 12:30 PM
Victor Cortes
Victor Cortes - avatar
+ 2
Yes, the error is because you're trying to increment a non-static variable from a static method. The second code is working because the variable is declared inside the static method. The count variable is just like any other variable inside a function and any operation can be done on it from inside the function
6th Jun 2022, 12:35 PM
XXX
XXX - avatar