8/30/09

Explain using static class member ..

A class member declared static is a single instance of that member shared by all instances of this class (that's why it is sometimes termed a class variable, as opposed to object variable). This feature has many uses: for instance, in order to create a file lock, one can use a static bool class member. An object trying to access this file has to check first whether the static (i.e., shared) flag is false. If it is, the object turns the flag on and processes the file safely, since other objects will now find that the flag is now on, and hence -- they cannot access the file. When the object processing the file is done, it has to turn off the flag, enabling another object to access it. How is a static member created?
class fileProc {
FILE *p;
static bool isLocked; //only a declaration; see definition below...
public:
bool isLocked () const {return isLocked; }
};

//somewhere outside the class definition:

bool fileProc::isLocked; //definition; initialized to 'false' by default. Note: no 'static' here

1 comment:

sujitkumar said...

Nice info. Thanks for sharing valuable info about about c++ Faqs. I want to learn c training this tutorial is really helpful. Thanks a lot. Keep sharing on updating tutorials……