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:
Use a dynamic_cast
as follows:
ClassA* SomeClass::doSomething(ClassA* a)
{
if (dynamic_cast(a)) {
...
} else if (dynamic_cast(a)) {
...
}
}
dynamic_cast
will return 0
in case ptr
is not a pointer of type T
, and will return a pointer of type T
otherwise.
dynamic_cast
can usually be avoided and is an indicator of bad design / code. If you can avoid it, try to do so, as it requires RTTI in your final executable.