Why is static_cast used in QT's official document

Viewed 259

https://doc.qt.io/qt-5/eventsandfilters.html

In QT's offical document, static_cast is used in code like

QKeyEvent *ke = static_cast<QKeyEvent *>(event);
...
MyCustomEvent *myEvent = static_cast<MyCustomEvent *>(event);

However in my experience, dynamic_cast should be used since this is a cast from base to derived Is there any special reason for the static_cast use?

2 Answers

It is perfectly alright to use static_cast if you are absolutely certain that the appropriate dynamic_cast would succeed. Using static_cast is faster than dynamic_cast since it involves no runtime checks.

The code you see in that Qt documentation is valid. Using static_cast may be used and replaces dynamic_cast only if you know for sure that the pointer you want to cast from points to the object of class you want to cast to. In your question you omit very important detail. Before performing static_cast it checks for the type:

if (event->type() == MyCustomEventType) {...}
Related