Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Tuesday, August 20, 2024

C++ class for displaying the count of the objects

Objective: Design a C++ class having static member function name showcount() which has the property of displaying the number of objects created of the class.


Code:

#include <iostream>

using namespace std;

class MyClass {

    // Static data member to keep track of the number of objects created

    static int objectCount;

public:

    // Constructor that increments the object count whenever a new object is created. The static member function showcount() is used to display the current value of objectCount. Since it is static, it can be called without an object and only accesses the static members of the class.

    MyClass() {

        objectCount++;

    }

    // Static member function to display the count of objects created

    static void showcount() {

        cout << "Number of objects created: " << objectCount << endl;

    }

};

// Initialize the static data member outside the class

int MyClass::objectCount = 0;

int main() {

    // Creating objects of MyClass

    MyClass obj1;

    MyClass obj2;

    MyClass obj3;

    // Displaying the number of objects created

    MyClass::showcount();

    return 0;

}

Output:



No comments:

Post a Comment