liveBook · Manning

Dynamic_cast

As explained in 100 C++ Mistakes and How to Avoid Them

dynamic_cast is a C++ run-time checked cast expression for converting within polymorphic class hierarchies or testing such conversions.

Mistake: assuming a base-class pointer can safely be treated as a derived-class pointer. dynamic_cast checks the conversion at run time: an incompatible pointer cast returns null, while an incompatible reference cast throws an exception. Check pointer results before using them; consider whether polymorphic behavior can avoid the cast. section 5.6

Listing 5.13 Using C++-style casts more reservedly and responsibly
struct B {
    virtual int compute() { return 0; }
};
struct D : public B {
    int n;
    D() : n(42) {}
    int compute() { return n; }
};
 
int main() {
    const char msg[] = "Hello, world";
    char* p = const_cast<char*>(msg);                         #1
    *(p+1) = 'a';
    std::cout << msg << '\n';
 
    int n = 0x2A2A2A2A;
    char* c = reinterpret_cast<char*>(&n);                    #2
    for (int i = 0; i < sizeof(int); ++i)
        std::cout << *(c+i);
    std::cout << '\n';
 
    // std::cout << static_cast<double*>(msg) << '\n';        #3
    std::cout << static_cast<double>(n) << '\n';              #4
 
    B* b = new B();
    D* d = dynamic_cast<D*>(b);                               #5
    if (d)
        std::cout << d->compute() << '\n';
    else
        std::cout << "incompatible downcast\n";
 
    return 0;
}

The example downcasts a pointer to a B object—not a D object—and checks for null before calling a derived-class method. section 5.6

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Explains pointer and reference failure results, but not run-time implementation details.
Examples
Shows a B pointer downcast to D and a null check before use.
What it assumes
Requires a base class with at least one virtual method for downcasting.
What you can do after
Diagnose incompatible pointer downcasts by checking whether the result is null.
How it connects
Connects downcasting to inheritance and polymorphism.

Also explained in

Compare how 2 books explain dynamic_cast →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.