Static Keyword - RJAE5/2143-OOP GitHub Wiki

Static Keyword

The static keyword in C++ is used to control the lifetime and visibility of variables and functions. When applied to a local variable, it extends its lifetime to the entire duration of the program, meaning the variable retains its value between function calls. When applied to an attribute of a class it becomes known as a class variables. When applied to a attribute or function, it ensures that the class variable or function is shared across all instances of the class, making it accessible without needing an object.

Example

// Global static variable: restricted to this file
static int globalCounter = 0;

// Function that uses a static local variable
void incrementCounter() 
{
    static int localCounter = 0;  // Retains its value between function calls
    localCounter++;
    std::cout << "Local Counter: " << localCounter << std::endl;
}

// Class with a static member variable
class MyClass 
{
public:
    static int classCounter;  // Static member variable
    void incrementClassCounter() 
    {
        classCounter++;
        std::cout << "Class Counter: " << classCounter << std::endl;
    }
};

// Define the static member outside the class
int MyClass::classCounter = 0;

int main() 
{
    // Demonstrating static global variable
    globalCounter++;
    std::cout << "Global Counter: " << globalCounter << std::endl;

    // Demonstrating static local variable
    incrementCounter();  // First call
    incrementCounter();  // Second call, localCounter retains value

    // Demonstrating static class member variable
    MyClass obj1, obj2;
    obj1.incrementClassCounter();  // Class counter shared across instances
    obj2.incrementClassCounter();

    return 0;
}

Important Notes

  • Static global variables are counterintuitively only accessible within the file that it originated in.
  • Static variables in general are store in a seperate part of memory and retain their value until the end of the program.
  • Static class variables are shared by all instances of the class and any change by any one object affects the variable for all instances.

Sources:

  1. https://www.geeksforgeeks.org/static-keyword-cpp/
  2. https://www.w3schools.com/cpp/ref_keyword_static.asp