Skip to main content
gamedev.net
🔒 Locked

RTTI and the this pointer

Started by ScrambledEgg 1 reply 450+ views
Original Post
ScrambledEgg
ScrambledEgg
  
#include <iostream.h>

class foo
{
public:
  bool isA(const type_info& type) const
  {  if(typeid(this) == type)
       return true;
     else return false;
  }
};

int main()
{  foo *myFoo = new foo();
   cout << myFoo->isA(typeid(foo*)) << endl;
   delete foo;
   return 0;
}
  
Why does isA() not return true? Is there a better way to accomplish what I''m trying to do? Thanks in advance to your replies.
Chris Hargrove
Chris Hargrove
You might not have RTTI enabled as a compiler option, or you may have some kind of mismatch in terms of pointers (using foo* instead of foo). An easy way to test would be to print out the "name" member of the type_info, i.e. typeid(this).name, and see the results.

However, be advised that checking the type_info for equality is not a correct form of "isA", since a class "morefoo" derived from class "foo" would fail if tested for "isA foo". You need something that handles a test against superclasses as well as the current class.

For standard RTTI, the way of doing this is via dynamic_cast<typeName>(objectPointer). If dynamic_cast returns a valid pointer to typename, the isA test is successful. If it returns null, the test fails. However, the typeName field in dynamic_cast is an actual type name, and not a type_info structure, so you are restricted to casting to classes known at compile time.

If this is an acceptable limitation, then using dynamic_cast should work for you. If you need dynamic casts to classes not known until runtime, then you'll need to implement an alternative RTTI mechanism of your own. The gamedev.net patterns section should be online soon (probably within the next day or so), and I have a sample implementation of such as a scheme in a pattern called Reflective Factory, as part of that section. Take a look if this kind of thing interests you.


Edited by - Chris Hargrove on December 6, 2000 11:30:43 AM
ScrambledEgg
ScrambledEgg
Thanks for the info. I see the patterns section is up and I will be taking a look at your article.

Topic Locked

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

Sign in to reply to this topic.