It's best practice never to use C-style casts for two main reasons:
- as already mentioned, no checking is performed here. The programmer simply cannot know which of the various casts is used which weakens strong typing
- the new casts are intentionally visually striking. Since casts often reveal a weakness in the code, it's argued that making casts visible in the code is a good thing.
- this is especially true if searching for casts with an automated tool. Finding C-style casts reliably is nearly impossible.
As palm3D noted:
I find C++-style cast syntax too verbose.
This is intentional, for the reasons given above.
The constructor syntax (official name: function-style cast) is semantically the same as the C-style cast and should be avoided as well (except for variable initializations on declaration), for the same reasons. It is debatable whether this should be true even for types that define custom constructors but in Effective C++, Meyers argues that even in those cases you should refrain from using them. To illustrate:
void f(auto_ptr<int> x);
f(static_cast<auto_ptr<int> >(new int(5))); // GOOD
f(auto_ptr<int>(new int(5)); // BAD
The static_cast
here will actually call the auto_ptr
constructor.