Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

dynamic_cast is a type conversion operator in C++ used primarily for safe, runtime downcasting and cross-casting within a polymorphic class hierarchy. It leverages Run-Time Type Information (RTTI) to inspect the virtual method table (vtable) and verify the validity of the cast during program execution.

Syntax

dynamic_cast<new_type>(expression)
  • new_type: Must be a pointer or a reference to a complete class type, or a pointer to void (void*).
  • expression:
    • If new_type is a pointer, expression must be a pointer to a complete class type.
    • If new_type is an lvalue reference, expression must be an lvalue of a complete class type.
    • If new_type is an rvalue reference, expression must be a glvalue or a prvalue of a complete class type (where a prvalue undergoes temporary materialization).

Technical Requirements

  1. Polymorphism: For downcasting (base to derived) or cross-casting (between sibling base classes in multiple inheritance), the source type of expression must be polymorphic. This means the base class must declare or inherit at least one virtual function (typically a virtual destructor). Attempting a runtime dynamic_cast on a non-polymorphic type results in a compilation error.
  2. RTTI: The compiler must have RTTI enabled to perform runtime type checks. If RTTI is disabled via compiler flags (e.g., -fno-rtti in GCC/Clang), dynamic_cast will fail to compile only when used for downcasting or cross-casting. Upcasting will still compile successfully without RTTI.

Execution Behavior and Failure Modes

The behavior of dynamic_cast depends strictly on whether new_type is a pointer or a reference. The following examples assume this polymorphic class hierarchy:
class Base {
public:
    virtual ~Base() = default; // Ensures Base is polymorphic
};

class Derived : public Base {};

1. Pointer Casting

When casting pointers, dynamic_cast checks if the dynamic type of the object pointed to by expression is a complete object of new_type (or derived from it).
  • Success: Returns a valid pointer of type new_type.
  • Failure: Returns a null pointer (nullptr) of type new_type. It does not throw an exception.
Base* basePtr = new Base();

// Fails at runtime: basePtr points to a Base object, not a Derived object
Derived* derivedPtr = dynamic_cast<Derived*>(basePtr); 

if (derivedPtr == nullptr) {
    // Cast failed gracefully
}

delete basePtr;

2. Reference Casting

Because C++ references cannot be null, dynamic_cast handles reference casting failures via the C++ exception handling mechanism.
  • Success: Returns a valid reference of type new_type.
  • Failure: Throws an exception of type std::bad_cast.
#include <typeinfo> // Required for std::bad_cast

Base baseObj;
try {
    // Fails at runtime: throws std::bad_cast
    Derived& derivedRef = dynamic_cast<Derived&>(baseObj);
} catch (const std::bad_cast& e) {
    // Cast failed
}

3. Void Pointer Casting

If new_type is void*, dynamic_cast determines the exact dynamic type of the object and returns a pointer to the most derived object (the complete object) pointed to by expression.
Base* basePtr = new Derived();
// Points to the start of the complete Derived object
void* completeObjPtr = dynamic_cast<void*>(basePtr); 
delete basePtr;

Compile-Time vs. Runtime Resolution

While dynamic_cast is known as a runtime cast, it does not always incur runtime overhead:
  • Upcasting (Derived to Base): If new_type is an accessible, unambiguous base class of the type of expression, dynamic_cast resolves entirely at compile-time. In this scenario, it behaves identically to static_cast, does not require the base class to be polymorphic, and does not require RTTI.
  • Downcasting / Cross-casting: Requires runtime resolution. The operator traverses the inheritance graph stored in the RTTI to determine if the target type is a valid cast for the current dynamic object.
Master C++ with Deep Grasping Methodology!Learn More