Why do global variables not apply to the entire class?

Example code with VS error line

Simply put, why is the test in the function body recognized while the test in the function declaration isn’t? Shouldn’t the two test variables be derived from the same thing?

It would make sense to me, if either all of the test variables are valid or none of the test variables are valid. I would expect there to be consistency instead of one being valid while the other isn’t.

>Solution :

The difference is in when the code runs. A default argument is evaluated when the function is defined. The body of a function is executed only when the function is called. If they both try to access the same global variable that is not defined yet, the first will fail, even though the second would work (as long as the variable is defined before the function is called).

Leave a Reply