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

- 49,934
- 160
- 51
- 83

- 325
- 3
- 10
-
1@Hariprasad But how? `static_cast` also uses pointer arithmetic, as does the implicit derived* to base* conversion. (Except possibly when virtual bases are involved; in that case, I believe some compilers use an additional level of indirection instead.) – James Kanze Dec 27 '13 at 10:00
-
@James Kanze: This was a theoretician's answer. *Strictly speaking* it **does** use pointer arithmetics, you can't argue that. As well as it uses RAM and ALUs. So that "formally speaking" that answer was correct. And absolutely useless :) – valdo Dec 27 '13 at 10:05
-
Agreed James. static_cast also uses pointer arithmatic. – hims Dec 27 '13 at 10:10
2 Answers
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.

- 150,581
- 18
- 184
- 329
-
Agree. Especially I like your preamble "Formally, of course, it's implementation defined". Without this all the theoreticians around there would down-vote your (correct) answer without mercy :) – valdo Dec 27 '13 at 09:59
-
1@valdo Actually, I put it there as a means of (formally) indicating that variation can be expected. I can't think of any other means of implementing it at the abstract level, but the low level details (particularly: how does the code know that it has a match) may vary considerably, and navigating a DAG (as opposed to a tree) which is located in read only memory (the usual case) requires some extra work as well. – James Kanze Dec 27 '13 at 10:05
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.

- 325
- 3
- 10