Static Member Functions of Class in C++

Like static member variable, we can also have static member functions in a class. A member function that is declared static has the following properties:

  1. A static member function can have access to only other static members (functions or variables) declared in the same class
  2. A static member function can be called using the class name (instead of its objects) as follows:
    class-name :: function-name;

Program below illustrates the implementation of these characteristics:

#include <iostream.h>
class test
     {
          private:
               int code;
               static int count;     //static member variable
          public:
               void setcode()
                    {
                         code = ++count;
                    }
               void showcode()
                    {
                         cout << "Object number: " << code << endl;
                    }
               static void showcount()     //static member function
                    {
                         cout << "Count: " << count << endl;
                    }
     };

     int test :: count;

     void main()
          {
               test t1, t2;

               t1.setcode();
               t2.setcode();

               test :: showcount();     //accessing static function

               test t3;
               t3.setcode();

               test :: showcount();     //accessing static function

               t1.showcode();
               t2.showcode();
               t3.showcode();
     }

Output of the above program would be:

count: 2
count: 3
Object number: 1
Object number: 2
Object number: 3

In the above program:

  1. The static member function showcount() displays the number of objects created till that moment
  2. A count of number of objects created is maintained by the static variable count
  3. The function showcode() displays the code number of each object
  4. Note that the statement:
    code=++count;
    is executed whenever setcode() function is invoked and current value of count is assigned to code. Since each object has its own copy of code, the value contained in code represents a unique number of its object

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *