logo of SA Coder
        Menu
sign in

      References



Understanding Static Class Members in C++



In C++, both data members and member functions of a class can be made static. When a data member is declared static, it means that only one copy of that variable will exist, and all objects of the class will share that variable. This saves memory and allows the class to provide access control to shared resources.



To declare a static data member in a class, use the static keyword before the member variable's declaration. However, you must provide a global definition for the static variable outside the class to allocate storage for it. Static variables are initialized to zero before the first object is created.



For instance, suppose you have several objects of a class that need to write to a specific disk file, but only one object can be allowed to write to the file at a time. In this case, you can declare a static variable that indicates when the file is in use and when it is free. Each object then interrogates this variable before writing to the file to provide access control.



Here's an example of how to use a static variable of this type to control access to a shared resource


copy

#include <iostream>
using namespace std;

class Resource {
private:
    static bool fileInUse;

public:
    void writeToFile() {
        // check if the file is already in use
        if (fileInUse) {
            cout << "File is currently in use. Please wait." << endl;
            return;
        }

        // file is available, set it to in use
        fileInUse = true;
        cout << "Writing to file..." << endl;

        // simulate file write time
        for (int i = 0; i < 1000000000; i++) {}

        // release the file for other objects to use
        fileInUse = false;
        cout << "Done writing to file." << endl;
    }
};

bool Resource::fileInUse = false;

int main() {
    Resource obj1, obj2;
    obj1.writeToFile(); // writes to file
    obj2.writeToFile(); // checks if file is in use and waits
    obj1.writeToFile(); // writes to file after obj2 is done
    return 0;
}



On the other hand, when a member function is declared static, it means that the function can be called independently of any object, and it does not have a this pointer. There cannot be a static and a non-static version of the same function, and a static member function cannot be virtual or declared as const or volatile.



One good use of a static member function is to preinitialize private static data before any object is created. For example:


copy

#include <iostream>
using namespace std;

class MyClass {
private:
    static int myData;

public:
    static void initializeData(int value) {
        myData = value;
    }

    void printData() {
        cout << "My data is: " << myData << endl;
    }
};

int MyClass::myData = 0;

int main() {
    MyClass::initializeData(42);
    MyClass obj;
    obj.printData(); // prints "My data is: 42"
    return 0;
}



In this example, the 'MyClass' class has a private member variable 'myData', which is a static variable, meaning that it is shared by all instances of the class. The class also has a public static member function 'initializeData', which takes an integer parameter value and sets the value of 'myData' to 'value'.



The 'main' function first calls 'initializeData' with an argument of 42, which sets the value of 'myData' to 42. An object of 'MyClass' is then created using the default constructor, and the non-static member function 'printData' is called on this object. This function simply prints the value of the static member variable 'myData' to the console.



The use of a static member variable and function in the MyClass class allows data to be shared across all instances of the class, and can be useful in situations where multiple objects need to access and modify a common piece of data.


Summary



Static data members allow multiple objects of a class to share a single variable, saving memory and providing access control to shared resources. Static member functions can be called independently of any object and can be used to preinitialize private static data. The article provides examples of both static data members and static member functions to demonstrate their use.



Please login first to comment.