[gameprogrammer] Re: detecting class type at runtime

  • From: Chris Eineke <gameprogrammer@xxxxxxxxxxxxxxx>
  • To: gameprogrammer@xxxxxxxxxxxxx
  • Date: Thu, 19 Apr 2012 19:43:17 -0400

On 12-04-18 09:09 AM, luo_hei@xxxxxxxx wrote:
I have the following:

class A { ... }
class B: public A {}
class C: public A {}

void dosomething(A *variable){

}

inside dosomething I need to know if variable is of type B or C at runtime, is
there some portable way to do this?

enum MyClassType {
  TypeA,
  TypeB,
  TypeC
};

class A {
   public:
     virtual MyClassType getMyType() = 0;
};

MyClassType A::getMyType() { return MyClassType::TypeA; }

MyClassType B::getMyType() { return MyClassType::TypeB; }

MyClassType C::getMyType() { return MyClassType::TypeC; }

As others have pointed out, there are better strategies for determining the type of an object. It comes down to if you can modify existing code or not.

Why do you need to know what sub-type an object is and what are you going to do with that information?

Best regards,
  Chris

---------------------
To unsubscribe go to http://gameprogrammer.com/mailinglist.html


Other related posts: