To understand the casting system, you need to dive into the object model.
The classic representation of a simple hierarchical model is containment: if B comes from A , then the object B actually contains the subobject A along with its own attributes.
With this model, downcasting is a simple pointer manipulation with an offset known at compile time, which depends on the location of memory B
This is what static_cast does: the static actor is duplicated as static because the calculation of what is needed to create is performed at compile time, whether it be pointer or conversion arithmetic (*).
However, when virtual inheritance of strokes in things tends to get a little more complicated. The main problem is that with virtual inheritance, all subclasses have the same instance of a subobject. To do this, B will have a pointer to A instead of the correct A , and an object of the base class A will be created outside of B
Therefore, during compilation it is impossible to derive the necessary arithmetic of the pointer: it depends on the type of runtime of the object.
Whenever a runtime type dependency exists, you need RTTI (RunTime type information), and using RTTI for translations is the dynamic_cast job.
In short:
- compile time:
static_cast dynamic_cast time: dynamic_cast
The other two are also compilations, but they are so specific that it is easy to remember why they are needed ... and they are smelly, so itβs better not to use them at all.
(*) As noted in the comments of @curiousguy in the comments, this is true only for downcasting. A static_cast allows you to level up, regardless of virtual or simple inheritance, although actuation is also not necessary.
Matthieu M. Sep 20 '10 at 7:02 2010-09-20 07:02
source share