Friday, November 20, 2026
HomeC Programmingtypeid, dynamic_cast and type_info with Examples

typeid, dynamic_cast and type_info with Examples


A perform receives a Form&. Is it a circle? More often than not the precise reply is “it mustn’t matter”: name a digital perform and let the thing resolve. However typically code actually does must know the concrete sort behind a base-class pointer, to unwrap a plugin, deal with one particular case or rely objects by variety. C++ solutions that query at run time with RTTI.

This information covers the 2 RTTI operators, typeid and dynamic_cast, together with std::type_info and std::type_index, what they price and the designs that normally make them pointless. Each program beneath was compiled and examined with GCC, Clang and MSVC (C++17 and C++20, warnings as errors), and every output is captured verbatim.

The Quick Reply

What’s RTTI in C++? Run-time sort identification: the language options that report an object’s precise (dynamic) sort whereas this system runs. They’re typeid, which returns a std::type_info describing a sort, and dynamic_cast, which converts a pointer or reference alongside a category hierarchy after checking that the thing actually has the goal sort.

When does RTTI work? Just for polymorphic courses, which means courses with at the least one digital perform. For different varieties, typeid experiences the static sort and dynamic_cast doesn’t compile.

Ought to I take advantage of it? Sparingly. A digital perform or std::variant normally expresses the identical logic higher. dynamic_cast is the precise device for cross-casting between interfaces and for code that can’t change the category hierarchy.

What Is RTTI in C++?

RTTI (run-time sort identification) is the C++ mechanism that lets a program uncover the dynamic sort of an object by way of a pointer or reference to a base class. The compiler shops sort data for each polymorphic class, normally subsequent to its digital perform desk, and typeid and dynamic_cast learn it at run time.

Two phrases matter all through:

  • Static sort: the sort the compiler sees within the declaration. In Form& form = circle;, the static sort of form is Form.
  • Dynamic sort: the kind of the thing really there at run time, right here Circle. Solely polymorphic courses carry sufficient data to recuperate it.

The three instruments, aspect by aspect:

Device Solutions End result on failure Wants a polymorphic class
typeid(expr) “What precisely is that this object’s sort?” Throws std::bad_typeid for a null pointer dereference For the dynamic sort, sure; in any other case it experiences the static sort
dynamic_cast<T*>(p) “Can I deal with this object as a T?” nullptr Sure (it doesn’t compile in any other case)
dynamic_cast<T&>(r) The identical, for a reference Throws std::bad_cast Sure
static_cast<T*>(p) Not a query: the programmer asserts the reply No test; a flawed solid is undefined habits No
The place RTTI finds the dynamic sort Form& form static sort: Form what the compiler sees the Circle object in reminiscence vtable pointer Circle information members dynamic sort: Circle Circle class information type_info: Circle base courses: Form digital features typeid(form) follows the vtable pointer and returns the type_info for Circle. Evaluating two outcomes: 1 to five ns. dynamic_cast<T*>(p) reads the identical information, then searches the base courses for T; nullptr if absent. Price is dependent upon the search: 3 to 57 ns. A category with no digital features has no vtable pointer, so there may be nothing to learn: typeid experiences the static sort and dynamic_cast doesn’t compile.
Determine 1: typeid and dynamic_cast learn sort data that the compiler shops for each polymorphic class (simplified; the precise format is dependent upon the compiler). Timings from the benchmark beneath.

typeid and std::type_info

typeid takes a sort or an expression and returns a reference to a std::type_info object. Two type_info objects evaluate equal precisely once they describe the identical sort.

The one transportable issues to do with a type_info are evaluate it, hash it and print its title(). The title itself is implementation-defined: GCC and Clang return a mangled title (7PolyDer), and MSVC returns class PolyDer. The examples print names by way of a small helper that demangles on GCC and Clang and drops MSVC’s class or struct prefix, so the output is identical on each compiler:

// type_name.h - a readable class title from std::type_info.
//
// type_info::title() is implementation-defined: GCC and Clang return a mangled
// title ("7PolyDer"), MSVC returns "class PolyDer" or "struct PolyDer". This
// helper demangles on GCC and Clang and drops MSVC's "class "/"struct " prefix,
// so the packages print the identical textual content in all places.
#pragma as soon as

#embody <cstdlib>
#embody <reminiscence>
#embody <string>
#embody <typeinfo>

#if outlined(__GNUG__)
#embody <cxxabi.h>
#endif

inline std::string readable_name(const std::type_info& sort)
{
    std::string title = sort.title();
#if outlined(__GNUG__)
    int standing = 0;
    std::unique_ptr<char, void (*)(void*)> demangled(
        abi::__cxa_demangle(title.c_str(), nullptr, nullptr, &standing), std::free);
    if (standing == 0 && demangled)
        title = demangled.get();
#endif
    for (const char* prefix : {"class ", "struct "})
        if (title.rfind(prefix, 0) == 0)
            title.erase(0, std::string(prefix).measurement());
    return title;
}

The primary program exhibits what typeid experiences in every case:

// typeid_basics.cpp - what typeid experiences for polymorphic and
// non-polymorphic courses, and the way std::type_index makes varieties usable as keys.
#embody "type_name.h"

#embody <iostream>
#embody <map>
#embody <reminiscence>
#embody <typeindex>
#embody <typeinfo>
#embody <vector>

// Polymorphic: has a digital perform, so objects carry their dynamic sort.
struct Form {
    digital ~Form() = default;
};
struct Circle : Form {};
struct Sq. : Form {};

// Not polymorphic: no digital features, so typeid sees solely the static sort.
struct Plain {};
struct PlainDerived : Plain {};

int primary()
{
    Circle circle;
    Form& form = circle;
    std::cout << "static sort of form:        " << readable_name(typeid(Form)) << 'n';
    std::cout << "typeid(form) (polymorphic): " << readable_name(typeid(form)) << 'n';

    PlainDerived derived;
    Plain& plain = derived;
    std::cout << "typeid(plain) (not polymorphic): " << readable_name(typeid(plain)) << 'n';

    // High-level const and references are ignored.
    std::cout << std::boolalpha;
    std::cout << "typeid(const Circle) == typeid(Circle):  " << (typeid(const Circle) == typeid(Circle)) << 'n';
    std::cout << "typeid(Circle&) == typeid(Circle):       " << (typeid(Circle&) == typeid(Circle)) << 'n';
    std::cout << "typeid(form) == typeid(Circle):         " << (typeid(form) == typeid(Circle)) << 'n';

    // typeid on a null pointer to a polymorphic sort throws std::bad_typeid.
    Form* nothing = nullptr;
    strive {
        std::cout << readable_name(typeid(*nothing)) << 'n';
    } catch (const std::bad_typeid&) {
        std::cout << "typeid(*nullptr) threw std::bad_typeidn";
    }

    // std::type_index wraps type_info so it may be a map key.
    std::vector<std::unique_ptr<Form>> shapes;
    shapes.push_back(std::make_unique<Circle>());
    shapes.push_back(std::make_unique<Sq.>());
    shapes.push_back(std::make_unique<Circle>());
    std::map<std::type_index, int> counts;
    for (const auto& s : shapes) {
        const Form& present = *s;    // typeid(*s) would name unique_ptr::operator* inside typeid
        ++counts[typeid(current)];
    }
    std::cout << "circles: " << counts[typeid(Circle)] << ", squares: " << counts[typeid(Square)] << 'n';
}

Output (an identical with GCC, Clang and MSVC):

static sort of form:        Form
typeid(form) (polymorphic): Circle
typeid(plain) (not polymorphic): Plain
typeid(const Circle) == typeid(Circle):  true
typeid(Circle&) == typeid(Circle):       true
typeid(form) == typeid(Circle):         true
typeid(*nullptr) threw std::bad_typeid
circles: 2, squares: 1

4 guidelines come out of this:

  • Polymorphic courses report the dynamic sort. typeid(form) is Circle, as a result of Form has a digital destructor.
  • Different courses report the static sort. typeid(plain) is Plain though the thing is a PlainDerived. No error, no warning: only a totally different reply.
  • High-level const and references are ignored. typeid(const Circle) and typeid(Circle&) each equal typeid(Circle).
  • Dereferencing a null pointer inside typeid throws std::bad_typeid as an alternative of crashing, however just for polymorphic varieties.

std::type_index (from <typeindex>) wraps a type_info so it may be copied and used as a key in std::map or std::unordered_map. Counting objects by dynamic sort is likely one of the few locations the place typeid is genuinely the only device.

Be aware the road that binds *s to a reference earlier than calling typeid. Writing typeid(*s) on a std::unique_ptr makes Clang warn that the expression “shall be evaluated regardless of getting used as an operand to ‘typeid’” (-Wpotentially-evaluated-expression), as a result of the operand is a perform name (unique_ptr::operator*) on a polymorphic sort. With -Werror, that warning stopped the construct till the expression was modified.

dynamic_cast: Checked Conversions

dynamic_cast converts a pointer or reference to a polymorphic class right into a pointer or reference to a different class in the identical hierarchy, and checks at run time that the thing actually has that sort:

// dynamic_cast_basics.cpp - downcasts that succeed and fail, the reference
// kind that throws, cross-casts between sibling bases, and casting to void*.
#embody <iostream>
#embody <reminiscence>
#embody <typeinfo>

struct Account {
    digital ~Account() = default;
};
struct Financial savings : Account {
    double fee = 0.025;
};
struct Checking : Account {};

// Two unrelated interfaces, and a category that implements each.
struct Printable {
    digital ~Printable() = default;
};
struct Serializable {
    digital ~Serializable() = default;
};
struct Report : Printable, Serializable {};

int primary()
{
    std::unique_ptr<Account> a = std::make_unique<Financial savings>();
    std::unique_ptr<Account> b = std::make_unique<Checking>();

    // Pointer kind: nullptr when the thing isn't of the requested sort.
    if (auto* s = dynamic_cast<Financial savings*>(a.get()))
        std::cout << "a is Financial savings, fee " << s->fee << 'n';
    if (dynamic_cast<Financial savings*>(b.get()) == nullptr)
        std::cout << "b isn't Financial savings: dynamic_cast returned nullptrn";

    // Reference kind: there is no such thing as a null reference, so failure throws.
    strive {
        Financial savings& s = dynamic_cast<Financial savings&>(*b);
        std::cout << s.fee << 'n';
    } catch (const std::bad_cast&) {
        std::cout << "dynamic_cast<Financial savings&>(*b) threw std::bad_castn";
    }

    // Cross-cast: from one base to a sibling base of the identical object.
    Report report;
    Printable* p = &report;
    Serializable* sz = dynamic_cast<Serializable*>(p);
    std::cout << "cross-cast Printable* -> Serializable*: " << (sz != nullptr ? "okay" : "failed") << 'n';

    // The 2 base subobjects dwell at totally different addresses inside Report.
    // dynamic_cast<void*> finds the beginning of the entire object from both one.
    const void* from_p = dynamic_cast<void*>(p);
    const void* from_sz = dynamic_cast<void*>(sz);
    std::cout << "each bases result in the identical object: " << std::boolalpha
              << (from_p == from_sz && from_p == static_cast<void*>(&report)) << 'n';
    std::cout << "Printable* and Serializable* maintain the identical deal with: "
              << (static_cast<void*>(p) == static_cast<void*>(sz)) << 'n';
}

Output:

a is Financial savings, fee 0.025
b isn't Financial savings: dynamic_cast returned nullptr
dynamic_cast<Financial savings&>(*b) threw std::bad_cast
cross-cast Printable* -> Serializable*: okay
each bases result in the identical object: true
Printable* and Serializable* maintain the identical deal with: false

This system covers the 4 varieties in on a regular basis use:

  1. Downcast with a pointer. dynamic_cast<Financial savings*>(a.get()) returns a legitimate pointer when a holds a Financial savings, and nullptr in any other case. The if (auto* s = ...) kind exams and declares in a single line.
  2. Downcast with a reference. There isn’t a null reference, so a failed dynamic_cast<Financial savings&> throws std::bad_cast. Use this kind when a mismatch is a bug slightly than an anticipated case. The exception dealing with information covers catching it correctly.
  3. Cross-cast. Report implements each Printable and Serializable. Given a Printable*, dynamic_cast<Serializable*> finds the Serializable a part of the identical object, one thing static_cast can not do as a result of the 2 bases are unrelated. That is the basic use of dynamic_cast with a number of inheritance: asking an object whether or not it additionally helps one other interface.
  4. Forged to void*. dynamic_cast<void*> returns the deal with of the whole object. The final two traces present why that issues: the Printable* and Serializable* level to totally different addresses inside the identical Report, and solely dynamic_cast<void*> maps each again to 1 deal with.

Upcasts (from derived to base) want no solid in any respect; they’re implicit and all the time secure.

What dynamic_cast refuses to compile

Two errors are caught at compile time. The take a look at suite builds each packages and passes provided that the compiler rejects them with an identical message:

// dynamic_cast wants a polymorphic supply sort: Level has no digital perform.
struct Level { int x = 0; };
struct Point3 : Level { int z = 0; };

int primary()
{
    Point3 p3;
    Level* p = &p3;
    Point3* again = dynamic_cast<Point3*>(p);   // error: Level isn't polymorphic
    return again ? 0 : 1;
}
// dynamic_cast can not begin from void*: there is no such thing as a sort data to learn.
struct Base { digital ~Base() = default; };

int primary()
{
    Base b;
    void* v = &b;
    Base* again = dynamic_cast<Base*>(v);   // error: void* isn't a pointer to a category
    return again ? 0 : 1;
}

GCC 13.3 and Clang 18 report them like this:

not_polymorphic.cpp:9:20: error: can not 'dynamic_cast' 'p' (of sort 'struct Level*') to sort 'struct Point3*' (supply sort isn't polymorphic)
not_polymorphic.cpp:9:20: error: 'Level' isn't polymorphic
from_void.cpp:8:18: error: can not 'dynamic_cast' 'v' (of sort 'void*') to sort 'struct Base*' (supply isn't a pointer to class)
from_void.cpp:8:18: error: 'void' isn't a category sort

The primary error is the explanation RTTI is tied to digital features: a category with out them has no place to retailer its sort data. For those who want dynamic_cast on a hierarchy, give the bottom class a digital destructor, which it ought to have anyway if objects are deleted by way of base pointers.

Why static_cast Is Not a Substitute

static_cast additionally converts a base pointer to a derived pointer, with no run-time price and no test. If the thing isn’t of the goal sort, the result’s undefined habits: this system reads reminiscence that belongs to another object, or to no object in any respect.

Whereas testing this text, changing dynamic_cast<Financial savings&>(*b) with static_cast<Financial savings&>(*b) (the place b holds a Checking) gave three totally different outcomes:

  • GCC 13 at -O2 warned with -Warray-bounds that the entry was “partly exterior array bounds”, as a result of it might see the thing’s actual measurement. At -O0 it mentioned nothing.
  • Clang 18 compiled it with out a warning at each ranges.
  • UndefinedBehaviorSanitizer caught it at run time: “member entry inside deal with … which doesn’t level to an object of sort ‘Financial savings’ … object is of sort ‘Checking’”.

So the compiler catches a foul static_cast solely by luck. Use static_cast for downcasts solely when the sort is already identified by development, and dynamic_cast each time it’s a query.

The Dynamic Sort Throughout Building and Destruction

An object’s dynamic sort adjustments whereas it’s being constructed and torn down. Inside a base-class constructor, the derived half doesn’t exist but, so the thing is, for RTTI and digital calls, simply the bottom:

// development.cpp - throughout a constructor or destructor, an object's
// dynamic sort is the category whose constructor or destructor is working.
#embody "type_name.h"

#embody <iostream>
#embody <typeinfo>

struct Widget {
    Widget() { report("Widget constructor"); }
    digital ~Widget() { report("Widget destructor"); }
    void report(const char* the place) const
    {
        std::cout << the place << ": typeid(*this) is " << readable_name(typeid(*this))
                  << ", variety() says " << variety() << 'n';
    }
    digital const char* variety() const { return "widget"; }
};

struct Button : Widget {
    Button() { report("Button constructor"); }
    ~Button() override { report("Button destructor"); }
    const char* variety() const override { return "button"; }
};

int primary()
{
    Button button;
    button.report("primary");
}

Output:

Widget constructor: typeid(*this) is Widget, variety() says widget
Button constructor: typeid(*this) is Button, variety() says button
primary: typeid(*this) is Button, variety() says button
Button destructor: typeid(*this) is Button, variety() says button
Widget destructor: typeid(*this) is Widget, variety() says widget

typeid(*this) and the digital variety() agree at each step: Widget inside Widget‘s constructor and destructor, Button in all places else. This is identical rule that makes a digital name in a constructor name the bottom model, and the explanation to not depend on typeid or dynamic_cast on this earlier than development finishes.

RTTI vs Digital Capabilities vs std::variant

Most code that switches on a sort with dynamic_cast could be written in a manner the compiler checks. This system beneath computes the entire space of a circle and a rectangle 3 ways:

// alternate options.cpp - one job achieved 3 ways: computing the world of blended
// shapes with dynamic_cast, with a digital perform and with std::variant.
#embody <iostream>
#embody <reminiscence>
#embody <type_traits>
#embody <variant>
#embody <vector>

namespace with_rtti {
struct Form { digital ~Form() = default; };
struct Circle : Form { double r; specific Circle(double r_) : r(r_) {} };
struct Rect : Form { double w, h; Rect(double w_, double h_) : w(w_), h(h_) {} };

// Each new form wants a brand new department right here, and the compiler can not warn if one is lacking.
double space(const Form& s)
{
    if (auto* c = dynamic_cast<const Circle*>(&s))
        return 3.0 * c->r * c->r;            // pi rounded to three retains the output actual
    if (auto* r = dynamic_cast<const Rect*>(&s))
        return r->w * r->h;
    return 0.0;                              // an unknown form slips by way of silently
}
}    // namespace with_rtti

namespace with_virtual {
struct Form {
    digital ~Form() = default;
    digital double space() const = 0;         // each form should implement it
};
struct Circle : Form {
    double r;
    specific Circle(double r_) : r(r_) {}
    double space() const override { return 3.0 * r * r; }
};
struct Rect : Form {
    double w, h;
    Rect(double w_, double h_) : w(w_), h(h_) {}
    double space() const override { return w * h; }
};
}    // namespace with_virtual

namespace with_variant {
struct Circle { double r; };
struct Rect { double w, h; };
utilizing Form = std::variant<Circle, Rect>;    // a closed set of varieties, no base class

double space(const Form& s)
{
    return std::go to([](const auto& v) -> double {
        utilizing T = std::decay_t<decltype(v)>;
        if constexpr (std::is_same_v<T, Circle>)
            return 3.0 * v.r * v.r;
        else
            return v.w * v.h;                // a brand new various fails to compile right here
    }, s);
}
}    // namespace with_variant

int primary()
{
    {
        utilizing namespace with_rtti;
        std::vector<std::unique_ptr<Form>> shapes;
        shapes.push_back(std::make_unique<Circle>(1.0));
        shapes.push_back(std::make_unique<Rect>(2.0, 3.0));
        double complete = 0;
        for (const auto& s : shapes)
            complete += space(*s);
        std::cout << "dynamic_cast:     complete space " << complete << 'n';
    }
    {
        utilizing namespace with_virtual;
        std::vector<std::unique_ptr<Form>> shapes;
        shapes.push_back(std::make_unique<Circle>(1.0));
        shapes.push_back(std::make_unique<Rect>(2.0, 3.0));
        double complete = 0;
        for (const auto& s : shapes)
            complete += s->space();
        std::cout << "digital perform: complete space " << complete << 'n';
    }
    {
        utilizing namespace with_variant;
        std::vector<Form> shapes{Circle{1.0}, Rect{2.0, 3.0}};
        double complete = 0;
        for (const auto& s : shapes)
            complete += space(s);
        std::cout << "std::variant:     complete space " << complete << 'n';
    }
}

Output:

dynamic_cast:     complete space 9
digital perform: complete space 9
std::variant:     complete space 9

All three give the identical complete. They differ in what occurs when somebody provides a Triangle:

Method Including a brand new sort Including a brand new operation Checked by the compiler
dynamic_cast chain Add a department in each perform that switches on the sort Write one new perform No: a lacking department silently returns 0
Digital perform Write one new class Add a perform to each class Sure: a pure digital have to be carried out
std::variant + std::go to Add the sort to the variant, then repair each customer Write one new customer Sure: a customer that misses a sort doesn’t compile

Choose by what adjustments extra typically. A category hierarchy that grows (plugins, UI widgets) fits digital features, as described within the information to polymorphism. A hard and fast set of varieties with many operations on them (tokens, messages, shapes in a geometry library) fits std::variant. A dynamic_cast chain is the device of final resort: when the hierarchy belongs to another person, or when just one or two name websites care a few particular case.

How Quick Are typeid and dynamic_cast?

“RTTI is sluggish” is half true. bench/cast_cost.cpp within the repository occasions every operation over 10 million calls on a hierarchy 5 ranges deep. The GCC and Clang ranges are over 5 runs at -O2 on an x86-64 Xeon at 2.10 GHz; the MSVC column is 2 Launch runs on a Home windows 11 PC, so evaluate it with the opposite columns by sample, not by digit:

Operation GCC 13.3 (ns) Clang 18 (ns) MSVC (ns)
Digital perform name 1.3 to 1.7 1.3 to 2.3 1.3
typeid(*b) == typeid(D5) 0.9 to 1.0 0.9 to 1.9 4.4 to 4.6
dynamic_cast to the precise sort 3.3 to three.8 3.1 to five.2 11.7 to 12.7
dynamic_cast 4 ranges up 42.0 to 47.5 42.0 to 47.8 10.3 to 11.8
dynamic_cast that fails 46.5 to 55.9 51.1 to 57.2 27.5 to 33.7
dynamic_cast cross-cast 17.9 to 21.6 20.9 to 27.7 23.0 to 23.9

Three issues stand out:

  • The fee is dependent upon the runtime library, not on the language. GCC and Clang share libstdc++ and provides practically the identical numbers. MSVC’s runtime is organized in a different way: its typeid comparability prices about 4 digital calls as an alternative of 1, and its dynamic_cast to the precise sort is slower, whereas strolling 4 ranges up is quicker than on libstdc++.
  • A failing dynamic_cast is the most costly case in all places (28 to 57 ns right here), as a result of the runtime has to go looking the entire hierarchy earlier than giving up. Code that tries a protracted checklist of casts till one succeeds pays that worth for each miss.
  • Absolutely the numbers are small. Tens of nanoseconds matter inside a loop over thousands and thousands of objects, and virtually nowhere else.

Measure by yourself compiler earlier than optimizing, and if a sizzling loop actually does change on sort, a digital name (1 to 2 ns on each compiler right here) is the sooner design anyway.

Turning RTTI Off

GCC and Clang settle for -fno-rtti, and MSVC accepts /GR-. Tasks use them to save lots of the house taken by sort data, for instance in embedded code or in giant codebases reminiscent of LLVM and Chromium. With RTTI off:

  • With GCC and Clang, typeid and dynamic_cast now not compile. GCC experiences “can not use ‘typeid’ with ‘-fno-rtti’” and “‘dynamic_cast’ not permitted with ‘-fno-rtti’”; Clang experiences “use of typeid requires -frtti” and “use of dynamic_cast requires -frtti” (each measured on the packages above).
  • Digital features and std::variant preserve working, which is another reason to desire them.
  • Exceptions nonetheless work: compilers preserve the sort data that catch wants even with RTTI off.

Widespread Errors with RTTI

  • Utilizing typeid or dynamic_cast on a category with no digital features. typeid silently experiences the static sort, and dynamic_cast doesn’t compile. Give polymorphic bases a digital destructor.
  • Evaluating title() strings as an alternative of type_info objects. Names are implementation-defined and never assured distinctive. Evaluate with == or use std::type_index.
  • Printing title() to customers or logs and anticipating readable textual content. GCC and Clang return mangled names; demangle them first.
  • Checking the pointer kind for failure however not the reference kind. dynamic_cast<T&> by no means returns null; catch std::bad_cast or use the pointer kind.
  • Lengthy if (dynamic_cast...) else if (dynamic_cast...) chains. They conceal a lacking case. Exchange them with a digital perform or std::variant.
  • Calling typeid(*this) or dynamic_cast on this in a constructor and anticipating the derived sort.
  • Utilizing static_cast for a downcast that could be flawed. It compiles, runs and corrupts reminiscence.

Key Takeaways

  • RTTI means typeid, std::type_info, std::type_index and dynamic_cast. It really works on polymorphic courses solely.
  • typeid experiences an object’s actual dynamic sort; evaluate outcomes with ==, by no means by title.
  • dynamic_cast checks a conversion: nullptr for pointers, std::bad_cast for references.
  • Cross-casting between interfaces and dynamic_cast<void*> are issues solely dynamic_cast can do.
  • A digital perform or std::variant is normally the higher design, and the compiler checks it.
  • A typeid comparability prices 1 to five ns; a dynamic_cast prices 3 to about 57 ns, most when it fails. The precise numbers rely on the compiler’s runtime library.

Conclusion

RTTI is C++’s manner of answering “what is that this object, actually?” at run time. typeid provides the precise reply, and dynamic_cast solutions the extra helpful query of whether or not an object can be utilized as a specific sort. Each work solely the place the language has stored sort data, in polymorphic courses, and each are greatest stored for the circumstances a design can not keep away from: cross-casting between interfaces, unwrapping objects from code you don’t personal and the occasional particular case. In every single place else, a digital perform or a variant says the identical factor in a kind the compiler can test.

For the remainder of C++’s sort system and object mannequin, see sensible pointers, compound varieties and the C++ part.

Supply Code and Assessments

rtti workflow status

All packages on this web page are within the fundamentals/rtti listing of the MYCPLUS C++ examples repository.

Construct and take a look at:

cmake -S . -B construct
cmake --build construct --config Launch
ctest --test-dir construct -C Launch --output-on-failure

What the construct checks.

  • Compilers: GCC and Clang underneath C++17 and C++20 with -Wall -Wextra -pedantic -Werror, and MSVC with /W4 /WX /permissive-.
  • Output: every of the 4 packages prints precisely the output proven on this web page, on each compiler.
  • Compile failures: dynamic_cast on a non-polymorphic class and from void* should fail to construct, with a compiler message that names the issue.
  • Sanitizers: on Linux, each take a look at additionally runs underneath AddressSanitizer and UndefinedBehaviorSanitizer.

The benchmark is constructed however not examined, as a result of its numbers rely on the machine.

What I Verified

Every part within the Ubuntu column was run for this text on Ubuntu 24.04 (x86-64, GCC 13.3, Clang 18.1, CMake 3.28). The Home windows column comes from run_all.ps1 within the repository, run on Home windows 11 (construct 26300) with MSVC.

Verify Ubuntu 24.04 Home windows 11
Construct with warnings as errors GCC and Clang, C++17 and C++20: handed MSVC /W4 /WX /permissive-, C++17 and C++20: handed
CTest: 4 output comparisons and a couple of packages that should not compile 6 of 6 in all 4 configurations 6 of 6 in C++17 and in C++20
AddressSanitizer and UndefinedBehaviorSanitizer, each take a look at 6 of 6, clear Not relevant
Valgrind memcheck, each program No errors, no leaks Not relevant
Deliberate errors {that a} take a look at should catch All 4 caught All 5 caught (4 shared with Linux, 1 Home windows-only)

Not coated: -fno-rtti builds of the take a look at suite (checked by hand above), 32-bit builds and compilers older than GCC 13, Clang 18 and present MSVC.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments