C++ instanceof?

Started by
23 comments, last by _the_phantom_ 18 years, 11 months ago
A cookie for the first C++ programmer who knows what I'm talking about. N'eways, I'm trying to find out what type of derivative an object is. Like this: Base object; if(Base instanceof Derivative1) {do something;} if(Base instanceof Derivative2) {do something different;} I loved this feature in Java, but is there an easy way to do it in C++?
Advertisement
if (typeid(object) == typeid(Derived1)){  // do something}
So... Muira Yoshimoto sliced off his head, walked 8 miles, and defeated a Mongolian horde... by beating them with his head?

Documentation? "We are writing games, we don't have to document anything".
Hmm... didn't work. But you did understand it, so you still get the cookie.
Use dynamic_cast:
BaseClass * object = new DerivedA;if ( dynamic_cast<DeviredA*>( object ) )   // do somethingelse if ( dynamic_cast<DeviredD*>( object ) )   // do something else// ...


HTH,
Pat
It should work, as long as you've enabled RTTI (some compilers by default disable RTTI since it costs a tiny bit of performance and is seldomly used).

Another option would be
template<typename CheckType, InstanceType>bool isInstanceOf(InstanceType &Instance) {  return (dynamic_cast<CheckType *>(&Instance) != NULL);}if(isInstanceOf<Base>(pTheInstance))  cout << "mooh!" << endl;

but this requires RTTI as well. If I'm remembering right, Boost also provides a macro which can perform the check at compile time (of course, not including downcasts and ill-casted pointers ;))

-Markus-
Professional C++ and .NET developer trying to break into indie game development.
Follow my progress: http://blog.nuclex-games.com/ or Twitter - Topics: Ogre3D, Blender, game architecture tips & code snippets.
In C++ you can check the type runtime as follows:

// Suppose you haveclass Car;class Ferrari : public Car;class BMW : public Car;and then a function:bool IsFerrari(Car *c){   // check if pointer of type Car can be converted to type Ferrari   Ferrari *f = (Ferrari *)c;   if (f != 0)              return true;   else      return false;}int main(){   Car *f = new Ferrari;   Car *b = new BMW;   IsFerrari(f);  // returns true   IsFerrari(b); // returns false      delete f;   delete b;}

The preferred way (even in Java) would be to provide the appropriate virtual member function in the Base class, overriding it in the Derived classes:

class Base{public:   virtual void DoStuff() = 0;};class Derived1 : public Base{public:   virtual void DoStuff()   {      // Do something   }};class Derived2 : public Base{public:   virtual void DoStuff()   {      // Do something else   }};


Base* b = GetAnObject();b->DoStuff();


Now, if in spite of this good advice, you really want to figure out whether you have a Derived1, Derived2 or even something derived from one of those classes, you may use, not typeid, which will only check for exact type matches, but dynamic_cast<Derived1>, which will check whether the object you have is really a Derived1 object - or an object derived from that class.

note: clb, your version doesn't work, a C-style cast "works" unconditionally, whether it is right or wrong.

Base* b = GetAnObject();if( Derived1* d1 = dynamic_cast<Derived1*>(b)){   // do something with d1}else if( Derived2* d2 = dynamic_cast<Derived2*>(b)){   // do something with d2}


Also note that you either need to have a virtual function in your Base class, or "enable RTTI" for dynamic_cast (and typeid, for that matter) to work properly.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Right, I use virtual functions for doing things differently, I just wanted other objects to find out what kind of object it is. For example, if the player hits the "board vehicle" button, it would loop through the objects, checking if each one is close enough to get in. However, I want it to make sure each one is a "Vehicle" before I try to get in it. Before now, the player was "boarding" the gun he was holding!


Thanks for the help guys!
Quote:Original post by clb
In C++ you can check the type runtime as follows:
bool IsFerrari(Car *c){   // check if pointer of type Car can be converted to type Ferrari   Ferrari *f = (Ferrari *)c;   if (f != 0)              return true;   else      return false;}



Are you sure that works?? IMHO C-style casts never fail (i.e. return null) unless the argument itself is null also. You'd have to use the dynamic_cast operator to achieve that functionality. Feel free to correct me if I'm wrong.
Quote:Original post by evanofsky
Right, I use virtual functions for doing things differently, I just wanted other objects to find out what kind of object it is. For example, if the player hits the "board vehicle" button, it would loop through the objects, checking if each one is close enough to get in. However, I want it to make sure each one is a "Vehicle" before I try to get in it. Before now, the player was "boarding" the gun he was holding!


Aha.

[google] "double dispatch".

This topic is closed to new replies.

Advertisement