> ## 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.

# C++ Dynamic Cast

`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

```cpp theme={"dark"}
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:

```cpp theme={"dark"}
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.

```cpp theme={"dark"}
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`.

```cpp theme={"dark"}
#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`.

```cpp theme={"dark"}
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.

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor C++ Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
