95. Don’t use C-style casts

Summary

Age doesn’t always imply wisdom: C-style casts have different (and often dangerous) semantics depending on context, all disguised behind a single syntax. Replacing C-style casts with C++-style casts helps guard against unexpected errors.

Discussion

One problem with C-style casts is that they provide one syntax to do subtly different things, depending on such vagaries as the files that you #include. The C++ casts, while retaining some of the dangers inherent in casts, avoid such ambiguities, clearly document their intent, are easy to search for, take longer to write (which makes one think twice)—and don’t silently inject evil reinterpret_casts (see Item 92).

Consider the following code, where Derived inherits ...

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.