Главная страница | назад

Article #17051: Global variables in a class

 Question and Answer Database

FAQ2051C.txt   Global variables in a class
Category   :C/C++ Language Issues
Platform    :All
Product    :C++Builder  ALL

How do i make it so that a variable is global to all
classes of type ______? 

This is a really easy yet cool thing to do.  To do this simple 
declare the variable you want global to that class static.  
Here is an example:

class TMyClass{
    static int RefCount;
    TMyClass  () { RefCount++; }
    ~TMyClass () { RefCount--; }

Now RefCount is global to any TMyClass you declare in the same
application. By incrementing every time that the constructer 
is called it will tell me how many instances of class TMyClass 
there are.

To set the RefCount var in your application to zero, use:

int TMyClass::RefCount = 0;

In the header after the class declaration.

7/2/98 10:32:32 AM

Last Modified: 01-SEP-99