Using static_cast
to cast an object to a type it doesn't actually have yields undefined behavior. The symptoms of UB vary widely. There's nothing that says UB can't allow the derived member function to be called successfully (but there's nothing that guarantees that it will, so don't count on it).
Here is the rule for downcasting using static_cast
, found in section 5.2.9 ([expr.static.cast]
) of the C++ standard (C++0x wording):
A prvalue of type "pointer to cv1 B
", where B
is a class type, can be converted to a prvalue of type "pointer to cv2 D
", where D
is a class derived from B
, if a valid standard conversion from "pointer to D
" to "pointer to B
" exists, cv2 is the same cv-qualification as, or greater cv-qualification than, cv1, and B
is neither a virtual base class of D
nor a base class of a virtual base class of D
. The null pointer value is converted to the null pointer value of the destination type. If the prvalue of type "pointer to cv1 B
" points
to a B
that is actually a subobject of an object of type D
, the resulting pointer points to the enclosing object
of type D
. Otherwise, the result of the cast is undefined.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…