Possible Duplicate:
How is dynamic_cast typically implemented?
Hi!
how does dynamic_cast actually work? where does the runtime know from whether some piece of memory actually fits the datatype or not?
Thanks!
Possible Duplicate:
How is dynamic_cast typically implemented?
Hi!
how does dynamic_cast actually work? where does the runtime know from whether some piece of memory actually fits the datatype or not?
Thanks!
dynamic_cast
does not deal with a raw "piece of memory".
The starting point is that objects in C++ are strongly typed.
From the type dynamic_cast
knows that the object is of polymorphic type, that it has one or more virtual member functions.
From that, in practice, it knows that the object has a vtable pointer.
From the vtable pointer it has access to type information of the most derived class. This is also the most basic use, writing dynamic_cast<void*>(p)
, where you get a void*
pointer to the full object. It's a special case.
From the vtable for the most derived class it depends on the compiler's choices in representing the type information. Since I've never needed to know, I don't know what the actual choices are with common compilers. But it would be natural to tie this information up to the typeid
functionality, then using associations from the vtable to the typeid
for the requested type.
On the basis of that one would expect typeid
to be faster than dynamic_cast
for the case where you want to check for only a specific most derived class.
However, as I recall that's not necessarily the case, and I don't know why... ;-)
dynamic_cast
only works when you have Run Time Type Information (RTTI) enabled (normally done by default). RTTI is extra information that is associated with each object which allows the dynamic_cast
operator to determine if the object matches the specified type.
You can obtain this in formation yourself using:
std::typeinfo type = typeid(*myobject);
Just be aware that the definition of typeinfo is platform dependent.