Wednesday, February 16, 2011

Static Data Members


Static Data Members:
 A data member can be made static by using prefix static. The default value for static data member is zero and other values can be initialized. The important property of such variable is that only one copy of that member is created for entire class and is shared by all the objects of the class. This type of variable is also called class variable. It is visible within the class but its life time is the entire program.
 Example:
 #include<iostream.h>
#include<conio.h>
  class fruit
     {
     private:
            static int count;
            char name[15];
     public:
       void get_name()
             { cout<<"\nEnter name of fruit\t";
               cin>>name;  }
           
        void display_name()
               {   cout<<"\nThe name of apple\t"<<name;  }

       void count_object()
             { count++; }
      
      void display_count()
             { cout<<"\nThe value of count i.e. no of objects "<<count;  }
       };

    int fruit::count;  //definition of static data member

 void main()
    {
    fruit m, a;
    m.get_name();
    a.get_name();
    m.display_name();
    a.display_name();
    m.count_object();
    a.count_object();
    m.display_count();
    a.display_count();
     }
Output:  
Enter name of fruit     mango
Enter name of fruit     apple
The name of apple       mango
The name of apple       apple
The value of count i.e. no of objects 2
The value of count i.e. no of objects 2


The above example shows a variable count as static. This variable is shared by all objects (here 2 objects) and counts the number of objects. The important point to be remembered is that static member variable must be defined outside the class definition. 

No comments:

Post a Comment