In object-oriented C++, static data members and functions offer a way to manage data and functionalities that are shared by all objects of a class, independent of any specific object instance. Here’s a breakdown of both concepts:
static
keyword. There’s only one copy of this variable shared by all objects of that class.::
) or directly using an object reference (both point to the same variable).main
function.class Counter {
public:
static int objectCount; // Static data member declaration
Counter() {
objectCount++; // Increment counter in constructor
}
static void PrintObjectCount() {
std::cout << "Number of Counter objects: " << objectCount << std::endl;
}
};
// Static data member initialization outside the class
int Counter::objectCount = 0; // Initial value for all objects
int main() {
Counter c1, c2, c3;
Counter::PrintObjectCount(); // Output: Number of Counter objects: 3
return 0;
}
static
keyword. Static member functions don’t have access to the this
pointer (which refers to the current object instance) and cannot directly access non-static data members of the class.::
) or through an object reference (both call the same function).class StringValidator {
public:
static bool IsValidLength(const std::string& str, int minLength, int maxLength) {
return str.length() >= minLength && str.length() <= maxLength;
}
};
int main() {
std::string name = "John";
if (StringValidator::IsValidLength(name, 3, 20)) {
std::cout << "Name is valid." << std::endl;
} else {
std::cout << "Name length is invalid." << std::endl;
}
return 0;
}
By understanding static data members and functions, you can create more efficient and reusable class designs in object-oriented C++.