static member functionsall the objects of the


Static Member Functions

All the objects of the class share static data members of a class. The example above demonstrates how to keep track of all the objects of a class which area in existence. Though, this function uses existing objects to invoke a member function getcount(), which returns the value of the static data member. What if the programme does not require to use objects to invoke this function and still the programme would like to know how many objects have been created? If there is no object how the member function is invoked? Further, as can be seen from the last output, the number of objects (count) remains similar at a given instance no matter which object is used to invoke the member function.  In fact, the use of existing objects, like in the above instance, is not an effective way to access the value of the static data member. A specific object should not be used to refer to this member, as it does not belong to that object; it belongs to the whole class. C++ gives a facility to define static function members, for the similar. That is, to invoke such a function, an object is not needed. It can be invoked with the name of the class. The programme given below illustrates its use.

 

                class counter

                 {

                  public :

                                                counter ();

                                                static int getcount();

 

                  private:

                                static int count;

                };

counter::counter ()

                 {

                                count++;

                 }

 

                int counter::getcount()

                 {

                                 }

 

int counter :: count = 0;        // INITIALIZATION OF  

                                    STATIC MEMBER.

void main()

                 {

                  counter c1,c2;

                                cout << " Count = " << counter :: getcount() << endl;

                                cout << " Count = " << counter :: getcount() << endl;

                  counter c3;

                cout << " Count = " << counter :: getcount() << endl;

 

                  counter c4,c5;

 

                                cout << " Count = " << counter :: getcount() << endl;

                                cout << " Count = " << counter :: getcount() << endl;

                  }

Output:

                Count = 2

                Count = 2

                Count = 3

                Count = 5

                Count = 5

 

 

Request for Solution File

Ask an Expert for Answer!!
C/C++ Programming: static member functionsall the objects of the
Reference No:- TGS0309472

Expected delivery within 24 Hours