Skip to main content
GameDev.net gamedev.net
🔒 Locked

Question about classes and RTTI

Started by UriKiller Jan 18, 2007 at 2:10 AM 5 replies 1k views
Original Post
UriKiller
UriKiller
I've noticed that when I declare a static member inside a class, it will be the same for all the child classes too so if I change it through a child class it will also change for all the others. What I'm trying to do is to somehow give a static id to each class type in a class hierarchy. For example, CLavrador derives from CDog which derives from CAnimal and CCat also derives from CAnimal. I want each one of them to have some integer so I can during runtime check it. If I have a CAnimal *p which points to a CDog and I write p->id it will be the static id of CDog. If virtual data members in a class were allowed, this would be also an easy task because each class would just redeclare the id variable and give it a value in the constructor. [Edited by - UriKiller on January 18, 2007 3:04:35 AM]
Nepherim
Nepherim
You might want to look into RTTI for this.

But a simple solution you could use is to give each class a virtual function that returns the type ID. So instead of p->id you'd have p->id(). The id method would simply return a single value (the id of the class) and you'd override the function for each class to give a different value.
UriKiller
UriKiller
Thanks, the virtual methods is a good idea.
UriKiller
UriKiller
Hmmmmm, I just checked the RTTI.
Something is not working when I use it.

class Base {};class Child : public Base {};void main (){	Base *base = new Base;	Child *child = new Child;	Base *pbase;	pbase = base;	const type_info &t1 = typeid (*pbase);	pbase = child;	const type_info &t2 = typeid (*pbase);}


after this, t1 is equal to t2, but I thought that the whole purpose of this is that it should make t2 contain the name of the Child class, because even though the pointer is a 'Base *' the actual class it is pointing to is Child.
Nitage
Nitage
Your base class has no virtual functions, so the typeid is resolved at compile time.
UriKiller
UriKiller
But still why isn't the typeid returning a type_info with the Child class?

*And I just changed the first line of the code:
class Base {virtual void a (){}};
and there is a runtime error: "Unhandled exception in Kernel32.dll. Microsoft c++ exception."

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.