Meaning of static object?

D

dover

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!
 
P

Phlip

dover said:
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?

It means that variable has scope limited to its location, but a lifespan
from before its first use to after its last use.

Each time control flow enters a scope where its available, and uses it, it
has the same identity and state as previous and subsequent times.

Tip: Give all identifiers the most restricted scope possible. This means
static objects at file scope are more restricted than static objects at
class scope.

Now look up "static function at file scope".
 
J

JKop

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,172
Messages
2,570,934
Members
47,477
Latest member
ColumbusMa

Latest Threads

Top