How do static member variables work in c++?

by clyde_reichert , in category: General Help , 2 months ago

How do static member variables work in c++?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by alyson_bogan , 2 months ago

@clyde_reichert 

In C++, static member variables belong to the class rather than individual objects of the class. They are shared by all objects of the class and can be accessed without creating an object of the class. Here's how they work:

  1. Declaration: Static member variables are declared in the class declaration, typically in the public or private section. They must be declared with the static keyword. For example:
1
2
3
4
class MyClass {
public:
    static int count;
};


  1. Definition: The static member variable needs to be defined outside the class, typically in the source file (.cpp). This is necessary to allocate memory for the variable. For example:
1
int MyClass::count = 0;


  1. Accessing the static member variable: The static member variable can be accessed using the class name followed by the scope resolution operator (::) and the name of the variable. For example:
1
MyClass::count = 10;


  1. Usage: Static member variables can be used just like any other variables. They can be modified and accessed in member functions or through objects of the class. For example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
void MyClass::incrementCount() {
    count++;
}

int main() {
    MyClass::count = 5;
    MyClass obj1;
    obj1.count = 7;
    obj1.incrementCount();
    cout << MyClass::count;  // Output: 8
    return 0;
}


Note: Since static member variables are shared a**** all objects of the class, modifying the variable using one object will reflect the change in all other objects and vice versa.