First, while new to C++, functional style casts are C-style casts. They do the same thing.
C-style casts first try to static_cast
, and if that doesn't work, does a reinterpret_cast
1. This is bad, because operations that are intended to be a simple change can become very strange.
As an example, suppose you have a Foo* f
and a completely unrelated class Bar
. You can (Bar*)f
and it will silently reinterpret the *f
to be a Bar
, likely leading to undefined behavior.
A static_cast
would only work in this situation if Foo
and Bar
were related types.
Now, even static_cast
can be too strong, so I often write up an implicit_cast
or non_cast
template that converts-without-casting. Similarly, I write as_const
that adds const
rather than requiring a const_cast
(which can both add and remove const
, and removing const
is far more dangerous than adding it).
It is somewhat annoying that there is no explicit safe cast in C++, and I do not know how to write one (one that will execute explicit
constructors, but will not cast "down" a type hierarchy like static_cast
will).
1 this is an over-simplification, but close enough to true.