Counting the Number of Objects of a Particular Class in a C++ Program

This program demonstrates how to count the number of objects that are created for a class in C++ at runtime. The idea is to have a variable that increments and counts everytime a new object has been created of a particular class. Therefore this program features what is known as the static type of variable of the class. A static variable is one that has only copy of itself no matter how many objects are created for that class. 


Let us suppose that there are 2 variables in a class named A and B. Further lets suppose that B is static while A is not and 10 objects have been created of this class. Therefore by definition, A type variables will have a count of 10 i.e. 10 different variables corresponding to the 10 different objects will exist. But only 1 object for B will exist i.e. the sole copy of B will be shared by all the 10 objects. Whenever any object checks for the current value of B, it will get the same present value. 

Therefore we put this property of a static variable to use and create a program that stores the number of objects created for a particular class by doing the following steps:

  • Creating a Integer type variable to store count in the class definition
  • Incrementing its value in the constructor(i.e. whenever a new object is created)


#include <iostream.h>
#include <conio.h>
class Counter
{
      public:
      static int count;
      Counter() { count++; }
      ~Counter() { count--; }
};
int Counter::count;

void f(); // Function Declaration

int main(void)
{
      clrscr();
      Counter o1;
      cout << "Objects in existence: ";
      cout << Counter::count << "\n";
      Counter o2;
      cout << "Objects in existence: ";
      cout << Counter::count << "\n";
      f();
      cout << "Objects in existence: ";
      cout << Counter::count << "\n";
      getch();
      return 0;
}
      
void f() // Function Definition

{
       Counter temp;
       cout << "Objects in existence: ";
       cout << Counter::count << "\n";
       // temp is destroyed when f() returns
}

1 comment:

  1. This is one of the common questions for programming in C and C++. Personally, I prefer C++ as a programming language. I find it easier to code in this language than in C. Anyway, I think that on your blog you have a good collection of the common questions that students are asked to answer when they are first learning the language. Thanks for sharing.

    ReplyDelete

Custom Search