Re: Casting always bad?
AbrahamLincolnIllinois@yahoo.com () wrote (abridged):
Arghh! Today things reached a new low. I used a dynamic_cast to cast
something to its exact class, and my colleagues criticized the use of a
dynamic cast, saying I should have just plain cast it in the C style,
or at least used a static_cast.
Arguably you should only use dynamic_cast if there is a chance it will
give a different result to static_cast. If you know they will be the same,
you can use:
assert( dynamic_cast<MyType *>(p) == static_cast<MyType *>(p) );
MyType *p = static_cast<MyType *>(p);
which is a common enough idiom to be worth putting in a library.
You should generally not use a c-style cast because they are less clear
about what is happening, and they are so powerful they tend to hide
mistakes.
1. The compiler requires that we enable RTTI if we use a dynamic cast.
(True. I would rather avoid this if I could.)
In my view it's worth it, especially in debug builds.
Do you have your own hand-crafted casting framework? A way of asking an
object for its type? A lot of people do - there's one in Microsoft's
Foundation Classes, for example. If you are going to casting (or its moral
equivalent), it's usually less error-prone to use the built-in mechanisms
then a hand-rolled framework.
2. The anti-casting frenzy was invented by authors, not programmers.
Some people are both, of course.
Although here we are not discussing whether to cast, but what kind of cast
to use. These are two different arguments. Are they getting muddled?
3. Those people are speaking from the viewpoint of some other language
where type coercion is handled more gracefully. In C++, you have to
cast.
Which other language? Was the difference more than syntactic? It would be
useful to hear what they are comparing C++ to.
4. The casting syntax was specifically designed by the C++ committee
in order to discourge casting. (this one surprises me)
Sort-of true. It was also considered important that they be readily
visible in the code, be greppable, etc.
-- Dave Harris, Nottingham, UK.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]