Count the number of objects using Static member function in C++

C++Server Side ProgrammingProgramming

Here we will see how to count number of objects are created from a specific class using some static member functions. The static members are class properties, not the object properties. For a single class there will be only one instance for static members. No new members are created for each objects.

In this problem we are using one static counter variable to keep track the number of objects, then static member will be there to display the count value.

When a new object is created, so the constructor will be called. Inside the constructor, the count value is increased. Thus we can get the output.

Example

#include <iostream>
using namespace std;
class My_Class{
   private:
      static int count;
   public:
      My_Class() { //in constructor increase the count value
         cout << "Calling Constructor" << endl;
         count++;
      } static int objCount() {
         return count;
      }
   };
int My_Class::count;
main() {
   My_Class my_obj1, my_obj2, my_obj3;
   int cnt;
   cnt = My_Class::objCount();
   cout << "Number of objects:" << cnt;
}

Output

Calling Constructor
Calling Constructor
Calling Constructor
Number of objects:3
raja
Published on 02-May-2019 12:20:02
Advertisements