a data declared as static within a class, in a program that I am using returns or assigns it in two functions and neither is static, when in theory, if we want to use static data in a function, this function must be static, right? Why doesn't the compiler say anything when we use static data in a non-static method? You should protest but why don't you?
Thank you!
It's the other way around: from a static function, you can't access non-static variables. But, from non-static functions, it is perfectly fine to access static variables.
The actual reasons for this behavior are as follows:
A non-static function receives a hidden first argument , called
this
. That argument is a pointer to the instance on which we operate.A static function does not receive the argument
this
, because by its own definition ofstatic
we are indicating that we do not want it.Anything
static
is not associated with any instance; its location in memory does not change for the life of the program, and is known to the compiler at all times.Now everything is clear:
From functions
static
you can't access anything you needthis
, because we don't have it: neither variables nor functions.From non-static functions, we can access any variables and functions of the class:
this
, so we can access the instance.static
do not needthis
, and are always accessible.