Special Casts

Dynamic Casts

The dynamic_cast<>() operator is part of the RTTI (run-time type information) engine in C++. It is a typecast, which unlike the standard C style (your-type-here) cast operator, performs a type conversion check when the operator is called (i.e. at runtime).

If the types are compatible (i.e. convertible), then the conversion occurs. If they are not, one of two things happen:

  1. If the variable acted upon is a pointer, then null is returned.
  2. If the variable acted upon is a reference, then an exception is thrown.

You can use the dynamic_cast<>() operator to work out the type of an object at run-time.


The following example shows how you can use dynamic_cast<>() to work out the type of an object at runtime. It uses the example where there are base and derived classes, and you wish to know to what one of these objects the pointer points to.

What Does This Mean For Embedded Devices?

If you use the dynamic_cast<>() operator in code that is going onto a microcontroller, this now means the entire RTTI engine has to be included (assuming you are not already using the typeid operator, which also uses the RTTI).

Note that RTTI is only availiable for functions which are polymorphic (i.e. have at least one virtual method), so by using RTTI-specific features, you are also implying you are using virtual methods, which is another resource cost on an embedded device.

Posted: January 5th, 2014 at 1:00 pm
Last Updated on: June 11th, 2017 at 12:27 pm

One Pingback/Trackback

One thought on “Special Casts”

Leave a Reply