Question

Can someone explain me how dynamic_cast works internally? And what is the role of Virtual Pointer in that?

Was it helpful?

Solution

Formally, of course, it's implementation defined, but in practice, there will be an additional pointer in the vtable, which points to a description of the object, probably as a DAG of objects which contain pointers to the various children (derived classes) and information regarding their type (a pointer to a type_info, perhaps).

The compiler then generates code which walks the different paths in the graph until it either finds the targeted type, or has visited all of the nodes. If it finds the targeted type, the node will also contain the necessary information as to how to convert the pointer.

EDIT:

One additional point occurs to me. Even if the generated code finds a match, it may have to continue navigating in order to ensure that it isn't ambiguous.

OTHER TIPS

What i have figure out is:

dynamic_cast knows that the 1. object is of polymorphic type, that it has one or more virtual member functions. 2. 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(p), where you get a void* pointer to the full object. It's a special case.

Please correct me or if you want to improve my answers, you are most welcome.

Thanks.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top