How do I check at runtime if an object is of type ClassA or of derived type ClassB? In one case I have to handle both instances separately
ClassA* SomeClass:
Others have pointed out that switching on types is usually a bad idea, so I won't. If you really have to do it, you can use the typeid operator to switch on the dynamic type of an object:
ClassA* SomeClass::doSomething ( ClassA* a )
{
if (typeid(*a) == typeid(ClassA)) {
/* parameter is of type base class */
} else if (typeid(*a) == typeid(ClassB)) {
/* a specific derived class */
} else {
/* some other derived class */
}
}
dynamic_cast is similar, but tests for convertibility, not equality:
ClassA* SomeClass::doSomething ( ClassA* a )
{
if (ClassB *b = dynamic_cast(a)) {
/* parameter is, or is derived from, ClassB */
} else {
/* parameter is, or is derived from, ClassA but not ClassB */
}
}
These only work if ClassA is polymorphic (that is, it has at least one virtual function).