Good $daytime,

> Date: Wed, 20 Jan 1999 21:57:48 -0500
> From: Yasushi Shoji <[EMAIL PROTECTED]>
> To: [EMAIL PROTECTED]
> Subject: summary: static variable in C++

> case 1:
> if you declare static variable outsize of the class,
> that means the variable is global. so that, it is possible
> to access the static variable from outsize of a object.

>   static int counter = 0;

>   class base {
>   public:
>       base(void) {counter++;}
>       ~base(void){counter--;}
>       int get_counter(void) {return counter;}
>   };

>   int main(void) {
>       base b;
>       counter += 1; // this is ok;
>       cout << b.get_counter();  // this prints 2
>   }

This works indeed, but brings another small but fundamental problem:

 o  Namespace pollution: from now on, you can't have another object
    named 'counter' without trouble.  This may be painful if your
    software is a library.

> case2:
> you should initialize(or define?) static variable
> outside of the class declaration.

Should you define it?  Yes.  Should you initialise it?  Perhaps.
Consider an example.

   class base {
   private:
       static int counter;
   public:
       base(void) {counter++;}
       ~base(void){counter--;}
       int whatever(void);
       int get_counter(void) {return counter;}
   };

You may never implement base::whatever() -- as long as you don't use
it.  If you do, you should put somewhere:

   int base::whatever()
   {
        ...
   }

The same applies to base::counter.  You write

   int base::counter;

or

   int base::counter = 0;

'static int counter' and 'int whatever(void)' are _declarations_, used
primarily for type checking.

'int base::counter' and 'int base::whatever()' are _definitions_ that
actually create such object.

'= 0' is a way to statically _initialize_ a variable.  One can also
think of '{ ... }' being sort of "initial value" for a function body :)

> case3:
> because, in my example, static variable is private,
> you need a static function if you want to access to
> that static variable without an object.

Sure.

  Regards,
  Willy.

--
"No easy hope or lies        | Vitaly "Willy the Pooh" Fedrushkov
 Shall bring us to our goal, | Information Technology Division
 But iron sacrifice          | Chelyabinsk State University
 Of Body, Will and Soul."    | mailto:[EMAIL PROTECTED]  +7 3512 156770
                   R.Kipling | http://www.csu.ac.ru/~willy  VVF1-RIPE

Reply via email to