Search code examples
c++casting

C++ dynamic_cast vs typeid for class comparison


Possible Duplicate:
C++ equivalent of instanceof

I was wondering what the difference between dynamic_cast and typeid is in regards to just class comparison (aside from dynamic_cast allowing access to the subclass's methods and typeid only being useful for class comparison). I found a two year old StackOverflow asking the same question: C++ equivalent of java's instanceof. However, it is two years old and I did not want to necro an old post (and I am unsure when typeid came out), so I thought to re-ask the same question with a slight difference.

Basically, I have class A and class B, which are both subclasses of abstract class C. Class C is being taken in as a parameter to a method and I want to determine if class C is really class A or class B. Both typeid and dynamic_cast work properly so this is more of a question of best practice/performance. I am guessing :

A* test = dynamic_cast<A*> someClassCVar
if (test != 0) { //it is of class A }

OR

if (typeid(someClassCVar) == typeid(A)) {
   //it is of class A
}

EDIT: Sorry, I forgot to include this bit of information. The ActiveMQ CMS documentation states to use dynamic_cast, but I think that is only because it assumes the user will want to access methods specific to the subclass. To me, it seems that typeid would be better performance if only a class comparison is needed: https://activemq.apache.org/components/cms/overview


Solution

  • There is an important difference between the two methods:

    if(A* test = dynamic_cast<A*>(&someClassCVar)) {
        // someClassCVar is A or publicly derived from A
    }
    

    Whereas:

    if(typeid(someClassCVar) == typeid(A)) {
       // someClassCVar is of class A, not a derived class
    }