Static functions and ID numbers for objects - C++ Class

C++ examples for Class:static member

Description

Static functions and ID numbers for objects

Demo Code

#include <iostream>
using namespace std;
class MyClass//from  w  ww . j av a2 s.  c o  m
{
   private:
   static int total;        //total objects of this class
   //   (declaration only)
   int id;                  //ID number of this object
   public:
   MyClass()                  //no-argument constructor
   {
      total++;              //add another object
      id = total;           //id equals current total
   }
   ~MyClass()
   {
      total--;
      cout << "Destroying ID number " << id  << endl;
   }
   static void showtotal()  //static function
   {
      cout << "Total is " << total << endl;
   }
   void showid()            //non-static function
   {
      cout << "ID number is " << id << endl;
   }
};
int MyClass::total = 0;         //definition of total
int main()
{
   MyClass g1;
   MyClass::showtotal();
   MyClass g2, g3;
   MyClass::showtotal();
   g1.showid();
   g2.showid();
   g3.showid();
   return 0;
}

Result


Related Tutorials