Static Member Function And Non Static Member Functions

Explain Static member function, differences between a static member function and non-static member functions

Static member function:-

Like static member variables we can also have static member functions. A member function that is declared as static has the following properties.
1)    A static member function can have access to only other static members(functions or variable) declared  
      in the same class.
2)    A static member function can be called using the class name a follows.
a.    Class_name : : function_name ( )
3)    A static member function also calls the class constructor explicitly.




The differences between a static member function and non-static member functions are as follows.

•    A static member function can access only static member(data and member functions) data and functions outside the class. A non-static member function can access all of the above including the static data member.
•    A static member function can be called, even when a class is not instantiated, a non-static member function can be called only after instantiating the class as an object.
•    A static member function cannot be declared virtual, whereas a non-static member functions can be declared as virtual
•    A static member function cannot have access to the 'this' pointer of the class.
•    A static or non static member function cannot have the same name.
#include<iostream.h>
#include<conio.h>
class test
{
        int code;
        static int count ;
    public:
        void setcode( )
        {    code =++ count;        }
        void showcode ( )
        {cout<<"object_number"<< code<<endl ;    }
       
static void showcount ( ) // static member function.
{    cout <<" count" <<count<<" \n";   
             cout<<”code =”<<code      //error , code is a non static member function.
}   
        };
    int test :: count;
void main ( )
        {
            test t1,t2,t3;
            t1. setcode ();
            t2. setcode ();
            test :: showcount ( );
            t3. setcode ( );
            test:: showcount ( );
                      t1. showcode ( );
            t2. showcode ( );
            t3. showcode ( );
        }
Output: -   
count : 2    count : 3
            object number :1object number : 2 object number : 3
 



Labels: