Page 100 - DCAP404 _Object Oriented Programming
P. 100

Unit 5: Static Members




          of using  a static  member is to declare  the global data which  should be  updated while  the  Notes
          program lives in memory.
          When a static member is declared private, the non-member  functions  cannot access  these
          members. But a public static member can be accessed by any member of the class. The static data
          member should be created and initialized before the main function control block begins.

          For example, consider the class account as follows:
                 class  account
                 {
                 private:
                         int  acc  _no;

                         static  int  balance;  //static  data  declaration
                 public:
                         void  disp(int  acc  _no);
                         void  getinfo(  );
                 };
          The static variable balance is initialized outside main() as follows:
                 int account::balance = 0;  //static data definition
          Consider the following Program which demonstrates the use of static data member count. The
          variable count is declared static in the class but initialized to 0 outside the class.
                 #include  <iostream.h>
                 #include  <conio.h>
                 class  counter
                 {
                 private:
                         static  int  count;
                 public:
                         void  disp();
                 };
                 int  counter::count  =  0;
                 void  counter::disp()
                 {
                         count++
                         cout  <<  “The  present  value  of  count  is  “  <<  count  <<  “\n”;
                 }
                 main()
                 {
                         counter  cntl  ;
                         for(int  i=0;  i<5;  i++)
                                cnt1.disp();
                         getche();
                 }




                                           LOVELY PROFESSIONAL UNIVERSITY                                   93
   95   96   97   98   99   100   101   102   103   104   105