C++ Static Class Members

www.igi‮f‬tidea.com

In C++, a static class member is a member that belongs to the class itself, rather than to individual objects of the class. A static member is shared among all objects of the class, and can be accessed without creating an object of the class. To declare a static member variable or function, you use the static keyword.

Here's an example of a class that has a static member variable:

class MyClass {
  public:
    static int count;
    MyClass() {
      count++;
    }
};

int MyClass::count = 0;

In this example, the class MyClass has a static member variable count that keeps track of the number of objects of the class that have been created. The MyClass constructor increments the value of count each time a new object is created. The count variable is initialized to 0 outside of the class definition.

You can access the static member variable using the class name and the scope resolution operator ::, like this:

MyClass obj1;
MyClass obj2;
std::cout << "Number of objects created: " << MyClass::count << std::endl;

In this example, we've created two objects of the MyClass class, which increment the value of the static member variable count. We then output the value of count using the class name and the :: operator.

In addition to static member variables, C++ also allows you to define static member functions, which can be called without an object of the class. Static member functions do not have access to the this pointer, since they are not associated with a specific object.

Here's an example of a class that has a static member function:

class MyClass {
  public:
    static void hello() {
      std::cout << "Hello, world!" << std::endl;
    }
};

int main() {
  MyClass::hello();
  return 0;
}

In this example, the class MyClass has a static member function hello that simply outputs the text "Hello, world!" to the console. We call the hello function using the class name and the :: operator in the main function. Since the hello function is a static member function, we don't need to create an object of the MyClass class to call it.