C++ · Module 9 · Lesson 81 min read

dynamic_cast & RTTI

RTTI: Run-Time Type Information

For polymorphic classes (with at least one virtual function), C++ keeps type information available at runtime.

dynamic_cast — safe downcasting

arduino
Shape* s = get_shape();
if (auto* c = dynamic_cast<Circle*>(s)) {
    c->radius();          // s really points to a Circle
} else {
    // not a Circle → dynamic_cast returned nullptr
}
Cast targetOn failure
pointer dynamic_cast<Circle*>(p)returns nullptr
reference dynamic_cast<Circle&>(r)throws std::bad_cast

Requires the base class to be polymorphic (have a virtual function).

static_cast downcasting

static_cast<Circle*>(s) has no runtime check — if s isn't really a Circle, using the result is undefined behaviour. Only use it when you're certain.

typeid (<typeinfo>)

scss
typeid(*s) == typeid(Circle)   // compare types
typeid(*s).name()              // implementation-defined name (often mangled, e.g. "6Circle")

For polymorphic types, typeid(*ptr) gives the dynamic (actual) type.

Design advice ⚠️

Lots of dynamic_cast is a design smell — you're doing manually what virtual functions should do:

arduino
if (dynamic_cast<Circle*>(s)) ... else if (dynamic_cast<Square*>(s)) ...   // ❌
s->draw();                                                               // ✅ virtual

Legitimate uses: checking for an optional capability (does this object also implement Saveable?), plugin systems, debugging.

Alternatives

  • Virtual functions (best)
  • std::variant + std::visit for a closed set of types (Unit 13)
  • Visitor pattern

Cost

dynamic_cast walks type information at runtime — slower than a virtual call. Some projects disable RTTI (-fno-rtti) for size/speed.

Example

C++
#include <iostream>
#include <memory>
#include <string>
#include <typeinfo>
#include <vector>

class Expense {
public:
    explicit Expense(double amount) : amount_(amount) {}
    virtual ~Expense() = default;
    virtual std::string kind() const = 0;
    double amount() const { return amount_; }
private:
    double amount_;
};

class Recurring {                                   // an optional capability
public:
    virtual ~Recurring() = default;
    virtual int every_days() const = 0;
};

class Food : public Expense {
public:
    using Expense::Expense;
    std::string kind() const override { return "Food"; }
};

class Rent : public Expense, public Recurring {
public:
    using Expense::Expense;
    std::string kind() const override { return "Rent"; }
    int every_days() const override { return 30; }
};

class Subscription : public Expense, public Recurring {
public:
    Subscription(double amount, std::string service) : Expense(amount), service_(std::move(service)) {}
    std::string kind() const override { return "Subscription"; }
    int every_days() const override { return 30; }
    const std::string& service() const { return service_; }
private:
    std::string service_;
};

int main() {
    std::vector<std::unique_ptr<Expense>> list;
    list.push_back(std::make_unique<Food>(450));
    list.push_back(std::make_unique<Rent>(15000));
    list.push_back(std::make_unique<Subscription>(799, "Netflix"));

    double monthly_fixed = 0;
    for (const auto& e : list) {
        std::cout << e->kind() << " Rs. " << e->amount();
        if (auto* r = dynamic_cast<const Recurring*>(e.get())) {      // capability check
            std::cout << " (repeats every " << r->every_days() << " days)";
            monthly_fixed += e->amount();
        }
        if (auto* s = dynamic_cast<const Subscription*>(e.get()))
            std::cout << " [" << s->service() << "]";
        std::cout << '\n';
    }
    std::cout << "Fixed monthly costs: " << monthly_fixed << '\n';

    const Expense& first = *list[0];
    std::cout << std::boolalpha << "first is Food? " << (typeid(first) == typeid(Food))
              << ", is Rent? " << (typeid(first) == typeid(Rent)) << '\n';
    try {
        const Rent& r = dynamic_cast<const Rent&>(first);              // reference cast fails -> throws
        std::cout << r.amount() << '\n';
    } catch (const std::bad_cast&) {
        std::cout << "dynamic_cast<const Rent&> threw std::bad_cast\n";
    }
    return 0;
}

/* Output:
Food Rs. 450
Rent Rs. 15000 (repeats every 30 days)
Subscription Rs. 799 (repeats every 30 days) [Netflix]
Fixed monthly costs: 15799
first is Food? true, is Rent? false
dynamic_cast<const Rent&> threw std::bad_cast
*/