93. Avoid using static_cast on pointers

Summary

Pointers to dynamic objects don’t static_cast: Safe alternatives range from using dynamic_cast to refactoring to redesigning.

Discussion

Consider replacing uses of static_cast with its more powerful relative dynamic_cast, and then you won’t have to remember when static_cast is safe and when it’s dangerous. Although dynamic_cast can be slightly less efficient, it also detects illegal casting (and don’t forget Item 8). Using static_cast instead of dynamic_cast is like eliminating the stairs night-light, risking a broken leg to save 90 cents a year.

Prefer to design away downcasting: Refactor or redesign your code so that it isn’t needed. If you see that you are passing a Base to a function that ...

Get C++ Coding Standards: 101 Rules, Guidelines, and Best Practices now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.