OOP

Static Data members and Functions

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:

1. Static Data Members:

Example:

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;
}

2. Static Member Functions:

Example:

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;
}

Key Points:

By understanding static data members and functions, you can create more efficient and reusable class designs in object-oriented C++.