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
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.
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.
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 }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With