Search code examples
c++rttitypeinfo

Trying to count instances of deriving classes, type_id doesn't work


I want to count all the instances of derivers from my class, I'm trying to do it like so:

.h file:

#ifndef _Parant
#define _Parant

#include<map>

class Parant
{
public:
    Parant();
    virtual ~Parant();
    static void PrintInstances();

private:
    static void AddInstance(const char* typeName);
    static std::map<const char*, int> InstanceCounter;
};

#endif

.cpp file:

#include "Parant.h"
#include <typeinfo>
#include <iostream>

using namespace std;

Parant::Parant()
{
    AddInstance(typeid(this).raw_name());
}


Parant::~Parant()
{
}


std::map<const char*, int> Parant::InstanceCounter;

void Parant::AddInstance(const char* typeName)
{
    InstanceCounter[typeName]++;
}


void Parant::PrintInstances()
{
    for(map<const char*,int>::iterator i = InstanceCounter.begin(); i != InstanceCounter.end(); i++)
    {
        cout << " typename: " << i -> first << " ;;" ;
        cout << " count: " << i -> second << endl ;
    }

}

I have two inheritors that look like this (the cpp contains empty implementations):

#pragma once
#include "parant.h"
class ChildA :
    public Parant
{
public:
    ChildA(void);
    virtual ~ChildA(void);
};

and this is the main function:

int main()
{
    ChildA a;
    ChildB b;
    ChildA a1;

    Parant::PrintInstances();
....

The result I get is:

 typename: .PAVParant@@ ;; count: 3

Why doesn't it work?

I changed it to

AddInstance(typeid(*this).raw_name());

of course it still doesn't work, though now I understand why... can I get it to work?


Solution

  • typeid(*this) in a constructor just yields the constructor's class (you had it typeid(this) but that's wrong anyway since it will just give you the type_info of a pointer). That's considered the dynamic type of the object during construction.

    Another difference there is that virtual functions called during construction won't end up in the derived class, but in the class where the call is made during construction.