C++ static member
Created By: chatGPT
In C++, a static member is shared among all instances of a class. It belongs to the class itself rather than to any individual object. This means that regardless of how many objects of the class you create, there is only one copy of the static member. You can use a static member to maintain state or to count the number of instances.
class MyClass {
public:
static int objectCount;
MyClass() {
objectCount++;
}
};
int MyClass::objectCount = 0;
int main() {
MyClass obj1;
MyClass obj2;
std::cout << "Number of objects: " << MyClass::objectCount;
return 0;
}
To define a static member variable, you generally do it outside of the class definition. Static member functions can also be defined, and these functions can access only static members of the class. They do not require an instance of the class to be invoked.
class MyClass {
public:
static void showCount();
static int objectCount;
};
void MyClass::showCount() {
std::cout << "Count: " << objectCount;
}
int main() {
MyClass::objectCount = 5;
MyClass::showCount();
return 0;
}
To use a static member function, you call it using the class name instead of an object. This is useful for utility functions related to the class that do not need instance-specific data.
class Utility {
public:
static int add(int a, int b) {
return a + b;
}
};
int main() {
int sum = Utility::add(3, 4);
std::cout << "Sum: " << sum;
return 0;
}