Dynamic_cast vs static_cast vs const_cast vs reinterpret_cast

(Last Updated On: May 14, 2010)

There seems to be come confusion going on between all the C++ specific casts versus the older C style casts. The inventor of C++ Bjarne Stroustrup said that they should be avoided altogether. So we focus on the three types built for C++, these include Regular cast vs. static_cast vs. dynamic_cast

The first one is a limited static_cast. This performs no runtime checks so you would only need of how you refer to a specific type of object. Again you do not need do any checks as they are unnecessary with static_cast. For example:
void func(void *data) {
// conversion from MyClass* -> void* is implicit
MyClass *c = static_cast(data);


int main() { MyClass c; start_thread(&func, &c).join(); }
You do not need to check MyClass as type so you do not do a runtime check for this.

As for dynamic_Cast, this is used for cases when you do not know what the dynamic object type will be. Do note that this can be used if you downcast or the argument type is polymorhphic. An example:

if(JumpStm *j = dynamic_cast(&stm)) {

} else if(ExprStm *e = dynamic_cast(&stm)) {


dynamic_cast will return a null pointer if the object referred does not contain the type casted as a base class. If you cast to a reference, a bad_cast exception will be thrown. The following would not be valid as the base case is not polymorphic (does not contain a virtual function).

struct Base { };
struct Derived : Base { };
int main() {
Derived d; Base *b = &d;
dynamic_cast(b); // invalid

You can always upcast with both static_cast and dynamic_cast.

Const_cast is like const_cast( expression ). This is used to add or remove const – ness or volatility from a variable.

Another type of cast is reinterpret_cast which simply casts one bit wise to another. This canb be used dangerously so I see no use for it. For instance, on could cast for integer pointer against a string pointer.

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

Subscribe For Latest Updates

Sign up to best of business news, informed analysis and opinions on what matters to you.
Invalid email address
We promise not to spam you. You can unsubscribe at any time.


Check NEW site on stock forex and ETF analysis and automation

Scroll to Top