C++: Naming instances of objects

Started by
2 comments, last by ElJoelio 18 years, 11 months ago
Hello Unreal Tournament had a neat way to identify instances of classes, which was stored as a property of the class: <class name><counter> e.g. the first instance of a CRocket spawned into the level would be named CRocket0, the next rocket would be CRocket1, etc. This was extremely useful for examining log files, as the name would be prepended to the log entry when a class wrote something. It also gave a human-readable way to identify objects, rather than using an ID number or pointer value. Is there a way I can do something like this in C++? Currently I am just using an incrementing counter which my objects grab a copy of on construction. This works, but I'd prefer the something easier to read. I understand C++ doesn't have reflection, but there may be ways around it? One way I thought of was to have each class manually set it's 'class name' on construction, but I'm sure for the odd class here and there I'd forget to name it, or name it incorrectly, or use an existing class' code as a base and forget to rename, etc.
Advertisement
If you have a chance, go to the bookstore and crack open "3D Game Engine Architecture" and read the section on Object Management, specifically RTTI.

What it looks like Unreal Tournament did was have a base object, and each inherited object set its class name and used a static counter to give each one a unique value.
yeah, use a static counter that increments on construction... andddd... append that number to typeid(this).name(). i think that should work.

i ran accross typeid awhile ago... didnt realize it had a name function too. quite handy.. just ran a search on it now.

#include <typeinfo>
Thanks for the replies.

I had previously experimented with RTTI, but failed due to the following...

I had a base object, CRoot, which all other classes ultimately derive from. CRoot has this function:

std::string CRoot::ClassName()    {    const type_info &ti = typeid(this);    return std::string(ti.name());    }


As the code was in CRoot, the type_info returned was always a 'class CRoot*'. However, if I change

const type_info &ti = typeid(this);


to

const type_info &ti = typeid(*this);


I get the correct (most-derived) class name! Yippee! Now I just have to keep track of how many of each type of class have been created, in order to correctly increment the counter on a per-type basis.

This topic is closed to new replies.

Advertisement