Yes it will work.
dynamic_cast
is based on RTTI. The information provided by RTTI here is enough to determine the actual dynamic type of the pointed to object. By definition, RTTI is a run time notion, as is the dynamic type of the pointed to object (the fact that Foo's definition is not available in a compilation unit where said cast is written is a compile time notion, with no relevance here).
- If the pointed to object is actually a Foo, the dynamic_cast will succeed at run time.
- If it is not a pointer to an object deriving from Abstract2, it will fail (returning a null pointer).
details
A possible implementation of dynamic_cast
is to look up a special member at the beginning of the object's memory layout (or it could be stored along the v-table). This structure could contain a value, which identifies the dynamic type of the object.
Somewhere, the compiler would have generated a static table, replicating all the information about your program inheritance diagram.
At run time, the cast would extract the type identifier of your instance, and check it against the static table. If this identifier refers to a type deriving from Abstract2, the cast is meaningful (and the code can return a pointer correctly offset to the Abstract2
interface of your object).
Even this naïve implementation never requires the knowledge of Foo
in the compilation unit where the
cast is written.