Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting instances of individual derived classes

Tags:

c++

I'd like to be able to count instances of classes that belong in the same class hierarchy.

For example, let's say I have this:

class A;
class B: public A;
class C: public B;

and then I have this code

A* tempA = new A;
B* tempB = new B;
C* tempC = new C;
C* tempC2 = new C;

printf(tempA->GetInstancesCount());
printf(tempB->GetInstancesCount());
printf(tempC->GetInstancesCount());

the result of that should print
1
1
2

The counting, ideally, should be done internally. Each class, and not some kind of manager, should know how many instances it has.

Any ideas?

Thanks!

like image 240
djcouchycouch Avatar asked Dec 03 '22 08:12

djcouchycouch


2 Answers

There is a problem with proposed solutions: when you create B you A constructor will be called automatically and thus increment count of A.

class A
{
public:
    A(bool doCount = true)
    {
        if (doCount)
            ++instanceCount_;
    }

    static std::size_t GetInstanceCount()
    {
        return instanceCount_;
    }

    virtual ~A(){}
private:
    static std::size_t instanceCount_;
};

class B: public A
{
public:
    B(bool doCount = true):A(false)
    {
        if (doCount)
            ++instanceCount_;
    }

    static std::size_t GetInstanceCount()
    {
        return instanceCount_;
    }
private:
    static std::size_t instanceCount_;
};

std::size_t A::instanceCount_ = 0;
std::size_t B::instanceCount_ = 0;
like image 165
Mykola Golubyev Avatar answered Dec 04 '22 21:12

Mykola Golubyev


Directly off my head:

  • Create an integer static field in each class. Watch out for integer overflow.
  • Initialize it to 0 in an emulated static constructor.
  • Increment it at each (nonstatic) constructor body. Decrement it in the destructor.
  • GetInstancesCount() is a static function that returns the value of your integer static field.

Note: See Mykola's comments. This would print 4 for A, 3 for B and 2 for C i.e. it would count one instance of B as "one A and one B", and one C as "one A, one B and one C". Which is in a way true, but is not what the question asks for. In other words, my answer is wrong :)

like image 40
Daniel Daranas Avatar answered Dec 04 '22 20:12

Daniel Daranas