-5

How to declare a variable in a class that will track the count of objects created? example Object obj; obj.object_count();

Kevin
  • 6,993
  • 1
  • 15
  • 24
Kinowe
  • 11
  • 4

1 Answers1

2

You can store the object count using a static class member. And increase its value in class constructors, decrease its value in destructor.

Please find comments inline:

#include <iostream>
#include <atomic>

class Object
{
public:
    Object()    // Constructor
    {
        // initialize the object
        // ...

        m_objCount++;   // Increase object count when creating object (In constructor)
    }

    Object(const Object& obj)   // Copy constructor
    {
        m_objCount++;
    }

    Object(Object&&) // Move constructor
    {
        m_objCount++;
    }

    ~Object()
    {
        m_objCount--;   // Decrease object count when destroying object
    }

    static int object_count()   // Define a static member function to retrive the count
    {
        return m_objCount;
    }

private:
    static std::atomic_int m_objCount;  // Use static member to store object count, 
                                        // use std::atomic_int to make sure it is thread safe
};

std::atomic_int Object::m_objCount; // Initialize static member

int main()
{
    Object obj;

    // prints "obj count: 1"
    std::cout << "obj count: " << obj.object_count() << std::endl;          // call object_count() with object
    std::cout << "obj count: " << Object::object_count() << std::endl;      // call object_count() with class name
}
zhm
  • 3,513
  • 3
  • 34
  • 55
  • 1
    You also need to allow for the copy constructor and move constructor. It would be good for OP to wrap this logic up in a class so that users of it can still follow Rule of Zero – M.M Jun 08 '18 at 02:46
  • Since `object_count()` is `static`, you can call it using the class type instead of an object variable: `fprintf(stdout, "obj count: %d\n", Object::object_count());` And why are you using `fprintf()` in C++ instead of using `std::cout`? `std::cout << "obj count: " << Object::object_count() << std:::endl;` – Remy Lebeau Jun 08 '18 at 02:48
  • Edited as suggested. – zhm Jun 08 '18 at 02:58
  • Your count should be atomic if you are using threads – Alan Birtles Jun 08 '18 at 06:01
  • @AlanBirtles Do you really think we need to consider multi-threading in this question? – zhm Jun 08 '18 at 06:03
  • @zhm yes, someone who doesn't know what they're doing is likely to stumble across this question and answer then wonder why they get strange results – Alan Birtles Jun 08 '18 at 06:07
  • @AlanBirtles Good point. Edited. – zhm Jun 08 '18 at 07:01