11

Possible Duplicate:
Finding the type of an object in C++

I have a question with checking pointers to see if they conform to a particular derived class and take necessary action.

Lets say I currently have 2 derived classes DerivedClass1 and DerivedClass2 and the base class BaseClass. I would like to check the following action.

Ptr<BaseClass> ptr;

if (ptr points to DerivedClass1) { action1 } else { action2 }

How do I check for ptr points to a particular DerivedClass?

Community
  • 1
  • 1
lordlabakdas
  • 1,163
  • 5
  • 18
  • 33

3 Answers3

22

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.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • thanks. this was my initial thought but I had the problem of having a const method in a particular class and a non const in another one, thus was trying to add this behavior in a new method. – lordlabakdas Aug 14 '12 at 11:27
15

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.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • 1
    I agree that we mostly should avoid this, but I needed it for a test method to confirm that an object was of a certain type. So there are use cases. Thanks! – Peter Apr 02 '22 at 17:20
9
if(dynamic_cast<DerivedClass1*>(ptr))
{
  // Points to DerivedClass1
}
else if(dynamic_cast<DerivedClass2*>(ptr)
{
  // Points to DerivedClass2
}
Mathieu Rodic
  • 6,637
  • 2
  • 43
  • 49
Aesthete
  • 18,622
  • 6
  • 36
  • 45
  • 1
    If there was a third level, say, `DerivedClass1_1` and `DerivedClass1_2`, the first `if` clause would treat them both as a `DerivedClass1` - That might or might not be what the OP wants. – Component 10 Aug 14 '12 at 11:40
  • 4
    @Component10 I've simply answered the OP's question. I don't condone this practice, and usually find this is only needed when _bad design decisions_ have been made. Thanks for pointing the inheritance situation out though, in case the OP decides to try something like this. – Aesthete Aug 14 '12 at 11:45