dover posted:
If a class defined as classA, what's the meaning of "static classA
objectA;", within a file scope or a function scope or a class member
function scope?
Many thanks!
class classA {};
--
static classA objectA;
--
File scope: the object can only be accessed from within
this particular file, this particular "translation unit",
which includes the header files includes the header files
"#include"ed into this file. It has the same effect when
applied to a function. Don't use "static" at file scope,
it's been superseded by "namespace".
Function scope: there's only one object. The object is
first created when the function is first called, but...
when the function finishes, the object lives-on to the next
function call. It's finally destroyed when the program
ends. Example:
unsigned char Blah()
{
static unsigned char times_called = 1;
return ++times_called;
}
Class scope: there's only one object. All instances of the
class, all objects created from the class are working with
the one sole object. As such, you don't even need an object
of the class to access the variable. "static" can also be
applied to a function in a class - this specifies that the
function does not need an actual object of the class to
work with.
#include <iostream>
class Blah
{
public:
static unsigned long blah;
char jack;
static unsigned long GetBlah()
{
//++jack; This line is illegal
return blah;
}
}
int main()
{
cout << Blah::GetBlah();
}
-JKop