Programming C++  «Prev 

C++ - Examples of static_cast

static_cast<char>('A' + 1.0);
x = static_cast<double>(static_cast<int>(y) + 1);

enum peer { king, prince, earl } a;
enum animal { horse, frog, snake } b;
....
a = static_cast<peer>(frog);

Use of static_cast is safer and can replace all existing cast expressions.
Still, casting should be avoided, as turning a frog into a prince is rarely a good idea.
static_cast can perform conversions between pointers to related classes, not only from the derived class to its base, but also from a base class to its derived.
This ensures that at least the classes are compatible if the proper object is converted, but no safety check is performed during runtime to check if the object being converted is in fact a full object of the destination type. Therefore, it is up to the programmer to ensure that the conversion is safe. On the other side, the overhead of the type-safety checks of dynamic_cast is avoided.

C++ explicit casts

Casts should be used carefully, because what you are actually doing is saying to the compiler.
So forget type checking and treat it as this other type instead. That is, you are introducing a hole in the C++ type system and preventing the compiler from telling you that you are doing something wrong with a type. What is worse, the compiler believes you implicitly and does not perform any other checking to catch errors. Once you start casting, you open yourself up for all kinds of problems. In fact, any program that uses a lot of casts should be viewed with suspicion, no matter how much you are told it must be done that way.
In general, casts should be few and isolated to the solution of very specific problems. Once you understand this and are presented with a buggy program, your first inclination may be to look for casts.
But how do you locate C-style casts? They are simply type names inside of parentheses, and if you start hunting for such things you will discover that it is often hard to distinguish them from the rest of your code.
Standard C++ includes an explicit cast syntax that can be used to completely replace the old C-style casts (of course, C-style casts cannot be outlawed without breaking code, but compiler writers could easily flag old-style casts for you). The explicit cast syntax is such that you can easily find them, as you can see by their names:

1) static_cast, 2) const_cast, 3) reinterpret_cast
1) static_cast, 2) const_cast, 3) reinterpret_cast