Skip to content
Quantoros

When is dynamiccast safe, and when does it return null or throw?

C++Level: IntermediateCasting & Type Conversions

When is dynamic_cast safe, and when does it return null or throw?

Hints
  • Identify types, object lifetimes and compile-time decisions.
  • Separate language guarantees from a particular compiler's behavior.

Answer

dynamic_cast: Runtime Type-Safe Downcasting

:Source: src/casting/dynamic-cast

The dynamic_cast operator performs runtime type checking for safe downcasting in polymorphic class hierarchies. It requires the source type to have at least one virtual function (typically the destructor) because it relies on RTTI (Run-Time Type Information) stored in the virtual table. For pointer casts, it returns nullptr on failure; for reference casts, it throws std::bad_cast. This is the safest way to navigate class hierarchies when the actual type is uncertain at compile time, such as when processing heterogeneous collections of objects.

#include <iostream>
#include <memory>

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

struct Derived : public Base {
  void greet() { std::cout << "Hello from Derived\n"; }
};

int main(int argc, char *argv[]) {
  auto base = std::make_unique<Base>();
  auto derived = std::make_unique<Derived>();

  // Failed downcast: base doesn't point to Derived
  auto d1 = dynamic_cast<Derived *>(base.get());
  std::cout << "base -> Derived: " << (d1 ? "success" : "failed") << "\n";

  // Successful upcast: Derived* -> Base*
  auto b2 = dynamic_cast<Base *>(derived.get());
  std::cout << "Derived -> Base: " << (b2 ? "success" : "failed") << "\n";
}

note:

dynamic_cast has runtime overhead due to RTTI (Run-Time Type Information). In performance-critical code where types are known, prefer static_cast.

Answer section

Source and licence: C/C++ Interview Cheatsheet — Chang Ning Tsai · MIT

Related questions