Checking if a pointer points to a particular class C++

If BaseClass is polymorphic (contains virtual functions), you can test:

if (dynamic_cast<DerivedClass1*>(ptr.get()))

But usually you should use dynamic dispatch as unwind suggests, possibly a Visitor pattern, for this sort of thing. Littering your code with dynamic_cast makes it hard to maintain. I use dynamic_cast almost NEVER.


if(dynamic_cast<DerivedClass1*>(ptr))
{
  // Points to DerivedClass1
}
else if(dynamic_cast<DerivedClass2*>(ptr)
{
  // Points to DerivedClass2
}

If you were to think a bit more object-orientedly, you would just make it a virtual method on the base class:

Ptr<BaseClass> ptr;

ptr->Action();

and have each class implement it as needed. I realize this isn't an actual answer, but it's an alternative way of accomplishing your goal which is often considered to be better, which is why I think it's worth mentioning.

Tags:

C++

Pointers