C++ examples for Class:static member
Count number of objects in memory at any given time.
#include <iostream> using namespace std; class MyClass/*from www. j av a 2 s . c o m*/ { private: static int s_Counter; int* intValue{ &s_Counter }; public: MyClass() { ++(*intValue); cout << "Constructing: " << GetValue() << endl; } ~MyClass() { --(*intValue); intValue = nullptr; cout << "Destructing: " << s_Counter << endl; } MyClass(const MyClass& rhs) : intValue{ rhs.intValue } { ++(*intValue); cout << "Copying: " << GetValue() << endl; } int GetValue() const { return *intValue; } }; int MyClass::s_Counter{ 0 }; MyClass CopyMyClass(MyClass parameter) { return parameter; } int main() { auto object1 = MyClass(); { auto object2 = MyClass(); } auto object3 = MyClass(); auto object4 = CopyMyClass(object3); return 0; }