CPB Mailing List

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: static functions



A couple of observations about the use of static declarations in the context
of C++ classes.

static int aVar; // scope of visibitlity is limited to the .cpp file. In
addition all instances of the class that is defined in that
                       // cpp file share the same variable (and value). I
found this the hard way by having weird side-effects
                       // between instances of the same class.


> int anotherFunction()
> {
>   static int beenHere; // declared in same memory segment as "foofoo"
>                        // but is only available to this function.  It
>                        // is not on the stack, and retains its value
>                        // between invocations of this function.  Also, it
>                        // is not initialized until the first call to
>                        // this function.
> }
>

The above is not completely true. Is initialized to zero on startup. But it
may be assigned an initial value in itsdeclaration  ...static bool beenHere
= false;...

> // Now some added C++ uses of static
>
> class Foo
> {
> public:
>   static int Method(); // You don't need a Foo instance to call this
>                        // method, it is scoped in the Foo class.  To
>                        // call it, use Foo::Method()
>   static int Count;    // Just like a global variable, only it must be
>                        // accessed with Foo::Count
> };
>

On member function and member data items above, complete scope on required
if access is from outside any instances of the class. From within the
instances of the class just access them as with any other member function or
data item. The difference is that you only have one copy of each, shared
between all instances of that class (class global data).

Von R Colborn
Cornerstone Systems, Inc.




W Komornicki's Home Page | Main Index | Thread Index