static field is shared among instances : static « Class « C++






static field is shared among instances

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

int SomeClass::count;

int main(void)
{
   SomeClass One(1, 999); 
   One.show_values();   
   
   SomeClass Two(2, 1000);
   Two.show_values();

   SomeClass Three(3);
   Three.show_values();
}
  
    
  








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.static counter
11.Update static field in member method
12.Reference static method along with class name