C++ examples for Class:static member
A Class that Counts the Number of Instances
#include <iostream> using namespace std; class MyClass//from w w w .j a v a 2 s. co m { private: static int s_Counter; int* intValue{ &s_Counter }; public: MyClass() { ++(*intValue); } ~MyClass() { --(*intValue); intValue = nullptr; } int GetValue() const { return *intValue; } }; int MyClass::s_Counter{ 0 }; int main() { auto object1 = MyClass(); cout << object1.GetValue() << endl; { auto object2 = MyClass(); cout << object2.GetValue() << endl; } auto object3 = MyClass(); cout << object3.GetValue() << endl; return 0; }