A question related to Regular cast vs. static_cast vs. dynamic_cast:
What cast syntax style do you prefer in C++?
- C-style cast syntax:
(int)foo - C++-style cast syntax:
static_cast<int>(foo) - constructor syntax:
int(foo)
They may not translate to exactly the same instructions (do they?) but their effect should be the same (right?).
If you’re just casting between the built-in numeric types, I find C++-style cast syntax too verbose. As a former Java coder I tend to use C-style cast syntax instead, but my local C++ guru insists on using constructor syntax.
What do you think?
It’s best practice never to use C-style casts for three main reasons:
As palm3D noted:
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:
The
static_casthere will actually call theauto_ptrconstructor.