devxlogo

A static class member

A 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
See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist