static class membersas we already know all the


Static Class Members

As we already know all the objects of the class have dissimilar data members but invoke the similar member functions. Though, there is an exception to this rule. If the data member is declared with the keyword static, then only one such data item is formed for the entire class, no matter how many objects it has. Static data members are useful, if all objects of a class must share a common data item. While, the visibility of this data item remains similar, the duration of this variable is for whole lifetime of the program.

For example, such a variable can be particularly useful if an object needs to know how many objects of its kind exist.

class counter

                 {

                  public :

                                                counter ();

                                                int getcount();

  private:

                                static int count;

                };

counter::counter ()

                 {

                count++;

                 }

 

int counter::getcount()

                {

                                return ( count );

                 }

 

     int counter :: count = 0;// INITIALIZATION OF STATIC MEMBER.

 

                void main()

                 {

                  counter c1,c2;

                                cout << " Count = " << c1.getcount() << endl;

                                cout << " Count = " << c2.getcount() << endl;

 

                  counter c3;

                                cout << " Count = " << c3.getcount() << endl;

                  counter c4,c5;

                                cout << " Count = " << c4.getcount() << endl;

                                cout << " Count = " << c5.getcount() << endl;

                  }

 

Output:

 

                Count = 2             // not 1 because 2 objects are already created.

                Count = 2

                Count = 3

                Count = 5

                Count = 5

 

 

Request for Solution File

Ask an Expert for Answer!!
C/C++ Programming: static class membersas we already know all the
Reference No:- TGS0309470

Expected delivery within 24 Hours