home *** CD-ROM | disk | FTP | other *** search
/ Beginning C++ Through Gam…rogramming (2nd Edition) / BCGP2E.ISO / source / chapter08 / static_critter.cpp < prev   
Encoding:
C/C++ Source or Header  |  2006-09-25  |  996 b   |  47 lines

  1. //Static Critter
  2. //Demonstrates static member variables and functions
  3.  
  4. #include <iostream>
  5.  
  6. using namespace std;
  7.  
  8. class Critter
  9. {
  10. public:
  11.     static int s_Total;     //static member variable declaration
  12.                             //total number of Critter objects in existence
  13.     
  14.     Critter(int hunger = 0);
  15.     static int GetTotal();  //static member function prototype
  16.     
  17. private:
  18.     int m_Hunger;
  19. };
  20.  
  21. int Critter::s_Total = 0;   //static member variable initialization
  22.  
  23. Critter::Critter(int hunger): 
  24.     m_Hunger(hunger)
  25. {
  26.     cout << "A critter has been born!" << endl;
  27.     ++s_Total;
  28. }
  29.  
  30. int Critter::GetTotal()     //static member function definition
  31. {
  32.     return s_Total;
  33. }
  34.  
  35. int main()
  36. {
  37.     cout << "The total number of critters is: ";
  38.     cout << Critter::s_Total << "\n\n";
  39.      
  40.     Critter crit1, crit2, crit3;
  41.       
  42.     cout << "\nThe total number of critters is: ";
  43.     cout << Critter::GetTotal() << "\n";
  44.     
  45.     return 0;
  46. }
  47.