[gameprogrammer] Re: detecting class type at runtime

  • From: Jonathan Dearborn <grimfang4@xxxxxxxxx>
  • To: gameprogrammer@xxxxxxxxxxxxx
  • Date: Wed, 18 Apr 2012 09:36:34 -0400

C++ does not have true reflection capabilities.  However, you can use RTTI
in the form of dynamic_cast:
B* b = dynamic_cast<B*>(variable);
if(b)
{
    // Use b
    return;  // return here or otherwise skip the C part below
}
C* c = dynamic_cast<C*>(variable);
if(c)
{
    // Use c
}

Otherwise, you can include the type info yourself:
class A
{
    enum TypeEnum {CLASS_B, CLASS_C};
    TypeEnum type;
};

void dosomething(A* variable)
{
    switch(variable->type)
    {
        case A::CLASS_B:
            {
                B* b = static_cast<B*>(variable);
            }
        break;
        case A::CLASS_C:
            {
                C* c = static_cast<C*>(variable);
            }
        break;
    }
}

Both of these methods are less than ideal...  You could use templates (and
specialize the functions you need to differentiate) to avoid breaking the
type system in this way.

Jonny D

Other related posts: