gpt-4.1-mini-2025-04-14· OpenAI
WildChat-4.8M (AI2)
write a program in c++ to implement static data member
- User
write a program in c++ to implement static data member
- Assistant
Sure! Here's a simple example of how to use a static data member in a C++ class. Static data members are shared by all instances of the class rather than each instance having its own copy.
Example: Counting the number of objects created using a static data member
#include <iostream> class MyClass { private: static int count; // static data member declaration public: MyClass() { count++; // increment count whenever a new object is created } static int getCount() { // static member function to access static data member return count; } }; // initialize static data member outside the class int MyClass::count = 0; int main() { std::cout << "Initial object count: " << MyClass::getCount() << std::endl; MyClass obj1; MyClass obj2; std::cout << "Object count after creating 2 objects: " << MyClass::getCount() << std::endl; MyClass obj3; std::cout << "Object count after creating 3 objects: " << MyClass::getCount() << std::endl; return 0; }