Image

Imagekenshinhimura wrote in Imagecpp

Reasons to Prefer C++ casts over Plain-Old-C-Type-Cast (POCT).

1. C++ style casts do exactly what you want it to do nothing more nothing less as opposed to POCT which _forces_ casting. Old-C coders might prefer POCT since it makes it very (very) easy to cast anything to just about anything (since the user can only work with pointers, and built-in types this isn�t much of a problem), however this is not the case in C++. In C++, you can define your own type (via classes, enums, structs, and others) which makes casting a little bit more complicated.
Let�s say I have an object sName (which is an instance of MyString), and someone (who doesn�t read documentation) thinks he can get away with doing a (char*)sName, however I did not define any conversion operator for char*. This would lead to erroneous program that compiles, but does not do what the user wanted to do because the POCT, _forced_ the cast to char*. The previous problem could have been prevented had the user done static_cast<char*>, the compiler would have given out an error preventing the code from compiling in the first place. This is only a trivial example (for clarity�s sake) though many such problems would probably plague your code when involving C++-User Defined Types.

2. C++ style casts documents your code for people who would maintain it. Casts are sometimes unavoidable in C/C++, in these types of code I would I would like to see up front why the casting needs to be done, and what exactly is this cast doing. If I see a million POCT�s in C++ code all of which involving User Defined Types, I probably couldn�t help but curse at the original coder (and mutter �Why God? Why???� heh). I�d be constantly checking (if the reason for reading the code is debugging) if the casts were properly done, and what the hell the casts are doing in the first place. Clearly, that potentially wastes the time where I could have spent looking for the _actual_ bug which wrong-casting would cause.
Had C++ casting been used, things would have been different. I could have known beforehand exactly what that cast does, all I have to know is _why_ that cast had to be done. Furthermore I wouldn�t have had to guess the nature of the cast when debugging, it would be easier to understand the code and focus on other sources of bugs.

There are other reasons of course, but I ran out of time... have to eat breakfast and go to work.

I left out the list of cons when using C++ casts to you guys, let me know what you think