Noah Roberts wrote:
Greg wrote:
You must a dynamic_cast when casting from a virtual base class to a
derived class (or the other way around). Using a static_cast for such a
conversion would lead to undefined behavior.
I don't believe that is accurate; if so please provide the clause
because there are many, many expert written books that show how to
write a safe and fast "polymorphic_cast" by performing a dynamic cast
and testing the result when in debug build but static cast otherwise.
A dynamic_cast can indeed be safely replaced with a static_cast to
convert from a derived to a base class - just as long as there is no
virtual inheritance involved. And given how rare virtual base classes
are in practice - it is not surprising that the fact that a
dynamic_cast is required in this case - rarely comes up.
The relevant clauses are §5.2.9/2 and §5.2.9/9 of which I quote the
first one here:
"An lvalue of type cv1 B, where B is a class type, can be cast to type
"reference to cv2 D", where D is a class derived (clause 10) from B, if
a valid standard conversion from "pointer to D" to "pointer to B"
exists (4.10), cv2 is the same cv-qualification as, or greater
cv-qualification than, cv1, and B is not a virtual base class of D.
....Otherwise, the result of the cast is undefined."
Note the qualification: "B is not a virtual base class of D".
Greg