Consider this simple hierarchy:
class Base { public: virtual ~Base() { } };
class Derived : public Base { };
Trying to downcast Base*
How can the
dynamic_castknow whetherDerived2was derived fromDerived(what ifDerivedwas declared in a different library)?
The answer to that is surprisingly simple: dynamic_cast can know this by keeping this knowledge around.
When the compiler generates code it keeps around the data about the class hierarchies in some sort of table that dynamic_cast can look up later. That table can be attached to the vtable pointer for easy lookup by the dynamic_cast implementation. The data neeeded for typeid for those classes can also be stored along with those.
If libraries are involved, this sort of thing usually requires these type information structures to be exposed in the libraries, just like with functions. It is possible, for example, to get a linker error that looks like "Undefined reference to 'vtable for XXX'" (and boy, are those annoying!), again, just like with functions.