static counter : static « Class « C++






static counter

  
#include <iostream>
using namespace std;
class SomeClass 
{
  public:
    static int count;
    SomeClass(int value) 
    { 
      count++; 
      my_data = value;
    }; 
    SomeClass(int value, int static_value) 
  {
      count = static_value;
      my_data = value; 
  };
    ~SomeClass(void) { count--; };
    int my_data;
};      

int SomeClass::count;

int main(void)
 {
   SomeClass One(1, 999); 
   cout << "One: " << One.my_data << ' ' << One.count << endl ;
   
   SomeClass Two(2);
   cout << "Two: " << Two.my_data << ' ' << Two.count << endl ;
   
   SomeClass Three(3);
   cout << "Three: " << Three.my_data << ' ' << Three.count << endl ;
}
  
    
  








Related examples in the same category

1.Static member variables and functions
2.static functions and ID numbers for objects
3.Using a static data member in a class
4.Static member data.
5.Accessing static members without an object.
6.Accessing static members using non-static member functions.
7.Static member functions.
8.static members in classes
9.Calculate salary using static members.
10.Update static field in member method
11.Reference static method along with class name
12.static field is shared among instances