Thursday, September 20, 2012

How to count the number of objects created of a class

#include <iostream>
using namespace std;

class Demo
{
    public:
        static int totalObject;
       
        Demo()
        {
            totalObject++;
        }
};

int Demo::totalObject(0);    //static variable initialized to 0

int main()
{
    Demo d1;
    Demo d2;
    Demo d3;
    Demo d4;
   
    cout << "\n Total no of object of Demo class is: " << Demo::totalObject << endl;
    return 0;
}


OUTPUT:

No comments:

Post a Comment