Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ dynamic_cast vs typeid for class comparison [duplicate]

Tags:

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 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: http://activemq.apache.org/cms/cms-api-overview.html

like image 726
Jon Avatar asked Mar 14 '12 15:03

Jon


People also ask

Is Static_cast faster than Dynamic_cast?

While typeid + static_cast is faster than dynamic_cast , not having to switch on the runtime type of the object is faster than any of them.

Can Dynamic_cast throw exception?

dynamic_cast will no longer throw an exception when type-id is an interior pointer to a value type, with the cast failing at runtime. The cast will now return the 0 pointer value instead of throwing.


2 Answers

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 } 
like image 103
Maxim Egorushkin Avatar answered Dec 01 '22 08:12

Maxim Egorushkin


it depends if post type identification processing needs a pointer on A or not.

cheking typeid will surely be faster (since they're compiler generated constant identifiers) but won't provide any A instance to manipulate so will oblige you to perform a dynamic_cast to get a A instance.

like image 42
dweeves Avatar answered Dec 01 '22 10:12

dweeves