# C++: Naming instances of objects

This topic is 4836 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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.

##### Share on other sites
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.

##### Share on other sites
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>

##### Share on other sites
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.

1. 1
2. 2
frob
14
3. 3
4. 4
5. 5
Rutin
12

• 12
• 10
• 57
• 14
• 15
• ### Forum Statistics

• Total Topics
632113
• Total Posts
3004182

×