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:
- If the variable acted upon is a pointer, then null is returned.
- 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.
Example
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 available 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.