cpp/language/dynamic cast

Safely converts pointers and references to classes up, down, and sideways along the inheritance hierarchy.

Syntax
If the cast is successful, returns a value of type. If the cast fails and is a pointer type, it returns a null pointer of that type. If the cast fails and is a reference type, it throws an exception that matches a handler of type std.

Explanation
For the convenience of description, " or the result is a reference to " means that "it is a glvalue of type ", which follows the convention of.

Only the following conversions can be done with, except when such conversions would cast away constness or volatility.

@1@ If the type of is exactly  or a less cv-qualified version of, the result is the value of , with type. (In other words, can be used to add constness. An implicit conversion and  can perform this conversion as well.) @2@ If the value of is the null pointer value, the result is the null pointer value of type. @3@ If is a pointer or reference to, and the type of  is a pointer or reference to , where  is a unique, accessible base class of , the result is a pointer or reference to the  class subobject within the  object pointed or identified by. (Note: an implicit conversion and can perform this conversion as well.) @4@ If is a pointer to a, and  is a pointer to , the result is a pointer to the most derived object pointed or referenced by. @5@ If is a pointer or reference to a , and  is a pointer or reference to the type  a runtime check is performed:
 * @a@ The most derived object pointed/identified by is examined. If, in that object,  points/refers to a public base of, and if only one object of  type is derived from the subobject pointed/identified by , then the result of the cast points/refers to that  object. (This is known as a "downcast".)
 * @b@ Otherwise, if points/refers to a public base of the most derived object, and, simultaneously, the most derived object has an unambiguous public base class of type, the result of the cast points/refers to that  (This is known as a "sidecast".)
 * @c@ Otherwise, the runtime check fails. If the is used on pointers, the null pointer value of type  is returned. If it was used on references, the exception std is thrown.

@6@ When is used in a constructor or a destructor (directly or indirectly), and  refers to the object that's currently under construction/destruction, the object is considered to be the most derived object. If is not a pointer or reference to the constructor's/destructor's own class or one of its bases, the behavior is undefined.

Similar to other cast expressions, the result is: