Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

dynamic_cast — checked casting in class hierarchies

dynamic_cast converts pointers and references within class hierarchies, checking conversions at runtime where required. A failed pointer cast returns nullptr, whereas a failed reference cast throws std::bad_cast.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

dynamic_cast<T>(expression)

dynamic_cast<T>(expression) converts pointers or references within class hierarchies. T must be a pointer or reference to a complete class type, or a pointer to optionally cv-qualified void. The operator cannot remove const or volatile qualifiers.

Downcasts to derived classes and cross-casts between inheritance branches require a polymorphic source type: a class with at least one virtual function. Success depends on the actual object and the public, unambiguous inheritance rules. An upcast to an accessible, unambiguous base class does not require polymorphism; an implicit conversion usually suffices.

A failed pointer check yields nullptr; a failed reference check throws std::bad_cast, declared in <typeinfo>. A null input pointer produces a null result pointer. A cast to a pointer to void requires the static pointee type of p to be polymorphic. If p is non-null, the result points to the most-derived object. The target pointee type must preserve any const or volatile qualifiers of the source pointee type. For example, if p points to a const but not volatile polymorphic type, use dynamic_cast<const void*>(p) rather than dynamic_cast<void*>(p). The operator does not validate dangling pointers: violating object-lifetime requirements can cause undefined behavior.

The example demonstrates success and both failure forms. It targets C++23; the supplied standard URL serves an evolving draft, not a frozen C++23 publication. The example was run in an isolated environment; no production runtime is attested.

Examples

#include <iostream>
#include <typeinfo>

struct Base {
    virtual ~Base() = default;
};

struct Derived : Base {
    int value = 42;
};

int main() {
    Derived derived;
    Base base;
    Base* good = &derived;
    Base* other = &base;

    if (auto* p = dynamic_cast<Derived*>(good)) {
        std::cout << p->value << '\n';
    }
    std::cout << std::boolalpha
              << (dynamic_cast<Derived*>(other) == nullptr) << '\n';

    try {
        (void)dynamic_cast<Derived&>(*other);
    } catch (const std::bad_cast&) {
        std::cout << "bad_cast\n";
    }
}

Result

42
true
bad_cast

The displayed code was run unchanged in an isolated environment. Its standard output (`stdout`) matched the stated output exactly.

Sources