C++ static functions and ID numbers for objects

Description

C++ static functions and ID numbers for objects

#include <iostream>
using namespace std;
class MyClass//ww  w .  j a  v  a2s .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;
}



PreviousNext

Related