Wednesday, February 16, 2011

Static Member Function


Static Member Function:
       Like static data member, member function can be made static by using keyword static before function name. A static function can access to only other static data members or static member functions. Again, static member function can be called using the class name instead of object name. It is called as
    class_name:: function_name(argument_list);
 
An example:      
  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++; }

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

     };
    int fruit::count;

 void main()
    {
    fruit m, a;
    m.get_name();
    a.get_name();
    m.display_name();
    a.display_name();
    m.count_object();
    a.count_object();
    fruit::display_count(); //accessing static member function
     }

Output: 
Enter name of fruit     banana
Enter name of fruit     apple
The name of apple       banana
The name of apple       apple
The value of count i.e. no of objects 2

No comments:

Post a Comment