"Mark" <> wrote in message
> can someone explain, purely for my information, how
> dynamic_cast is implemented using only C++ language
> facilities.
I think one way to implement it is this: The virtual pointer of a class
points to the virtual table, in the virtual table is a pointer to a
std::type_info object that represents the type info for class, and there is
also a pointer to the virtual table of the parent class.
Suppose you have
Something * s = new MoreDerivedSomething();
Now when you say dynamic_cast<DerivedSomething*>(s), that system gets the
virtual pointer of 's', namely something like s.__vptr. Then check if the
type_info object pointed to in DerivedSomething is the same as the type_info
object pointed to by MoreDerivedSomething. They're not equal. So then
traverse to the virtual table of the parent class, which is the virtual
table of class DerivedSomething and repeat the test. If there is no parent
class then dynamic_cast returns NULL.
This algorithm is O(N) where N is the depth of the hierarchy. Furthermore,
comparing two type_info objects for equality may be O(M) where M is the
length of the class name including namespaces, because there may be multiple
copies of std::type_info objcets for a single class or even multiple copies
of the virtual table, so std::type_info:

perator== would have to compare
class names.
This is pretty slow. I'm sure dynamic_cast is required to be a fast
operation. Is it O(1)? How might one achieve this?