Pages

Jul 11, 2013

Static Variable in Class

This is a very simple example differentiating static  member variables and  regular member variables of the class.

I will be updating this post later with more examples on static variables and  functions

#include <iostream>
using namespace std;
class staticExample{
      int mydata;
      static int count; // Declaration
 public:

      staticExample( ){
      mydata = 50;   // static variable cannot be initialized
      count +=1;     // inside the class becoz d variable is SAME
      mydata++;      // for each class object. However, mydata
}                    // is unique for each class object.
                     // As we know, obj1->mydata is different   from obj2->mydata
                     // but, obj1->count is equal to obj2->count ... all the time
                  void getData(){
               cout<<"mydata : "<<mydata<<" count : "<<count<<endl;
          }
};
int staticExample :: count = 50; // Initialization, out side the class

int main(){
     staticExample john;
     john.getData();

     staticExample alex;
     alex.getData();
}

No comments:

Post a Comment