Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Info

In C++, static members of a class refer to variables and methods that belong to the class itself rather than to individual instances (objects) of the class. A static member is shared among all instances of a class and is only initialized once when the class is loaded. To declare a static member, you use the static keyword in the member's declaration.

  • If a function of a class is static, in the class definition, it is declared using the keyword static in its heading.

  • If a member variable of a class is static, it is declared using the keyword static,

  • A public static member, function, or variable of a class can be accessed using the class name and the scope resolution operator.

Here's an example of a static class member:

Code Block
languagecpp
class MyClass {
public:
    static int count;    // static class member
    
    MyClass() {
        count++;         // increment count on each object creation
    }
};

int MyClass::count = 0;   // initialize the static member outside the class definition

int main() {
    MyClass obj1;
    MyClass obj2;
    MyClass obj3;
    
    cout << MyClass::count << endl;   // prints "3"
    
    return 0;
}

In this example, we have defined a static class member count in the MyClass class. We have also defined a constructor that increments count on each object creation. Finally, we have initialized the static member outside the class definition.

In the main function, we create three objects of the MyClass class, which results in count being incremented three times. We then print the value of count using the class name, without needing an object of the class.

Static class members are useful when you need to share data or behavior among all objects of a class. They can also be used to maintain a count of objects of a class, as shown in this example.