Ensuring a Single Copy of a Member Variable, Using a static member variable - C++ Design Pattern

C++ examples for Design Pattern:Singleton

Description

Ensuring a Single Copy of a Member Variable, Using a static member variable

Demo Code

                                                     
class MyClass {//from w  w w.  j  a  v  a  2s.c  om
public:
    int getCount() {return count;}
    MyClass();
protected:
    static int count;
};
                                                     
int MyClass::count = 0;
                                                     
MyClass::MyClass() {
   count++;
}
                                                     
#include <iostream>
                                                     
using namespace std;
                                                     
int main() {
   MyClass a;
   MyClass b;
   MyClass c;
                                                     
   cout << a.getCount() << endl;
   cout << b.getCount() << endl;
   cout << c.getCount() << endl;
}

Result


Related Tutorials