Static Class Members in C++

Static data members are used when only one copy of the variable exists and all the objects of that class share that variable. It is mostly used to synchronize various objects accessing a shared variable. Below is a simple C++ program representing this functionality –

#include <iostream>

using namespace std;

class shared {
      static int resource; //declaration
      public:
             int get_resource();
             void free_resource() { resource = 0; }
};

int shared::resource;//definition
int shared::get_resource(){
    if(resource){
         return 0;
    }
    else{
        resource = 1;
        return 1;
    }
}

main(){
       shared ob1;
       shared ob2;
       
       if(ob1.get_resource()){
           cout << "Ob1 now uses resource\n";
       }
       if(!ob2.get_resource()){
           cout << "Ob2 waits for resource\n";
       }
       ob1.free_resource();
       if(ob2.get_resource()){
           cout << "Ob2 now uses resource\n";
       }
       return 0;
}

Output:

Ob1 now uses resource    
Ob2 waits for resource  
Ob2 now uses resource

Static member functions could only access members of a class. They could access other global functions and data. Static member functions can never have ‘this’ pointer. Also, there cant be both static and non-static version of the same function. Below is a simple C++ program to illustrate the use of static functions.

#include <iostream>

using namespace std;

class shared {
      static int resource; //declaration
      public:
             static int get_resource();
             void free_resource() { resource = 0; }
};

int shared::resource;//defenition
int shared::get_resource(){
    if(resource){
         return 0;
    }
    else{
        resource = 1;
        return 1;
    }
}

main(){
       shared ob1;
       shared ob2;
       
       /*get_resource() is static so may be called independent of any object */
       
       if(shared::get_resource()){
           cout << "Ob1 now uses resource\n";
       }
       if(!shared::get_resource()){
           cout << "Ob2 denied resource\n";
       }
       ob1.free_resource();
       if(ob2.get_resource()){ // could also call using object syntax
           cout << "Ob2 now uses resource\n";
       }
       return 0;
}

Output:


Ob1 now uses resource    
Ob2 waits for resource  
Ob2 now uses resource