Static cast in C++

The static_cast operator performs a non-polymorphic cast.
It can be used for any standard conversion.
No run-time checks are performed.

The static_cast operator can be used for operations such as converting a pointer to a base class to a pointer to a derived class. Such conversions are not always safe.

In general you use static_cast when you want to convert numeric data types such as enums to ints or ints to floats, and you are certain of the data types involved in the conversion. static_cast conversions are not as safe as dynamic_cast conversions, because static_cast does no run-time type check, while dynamic_cast does. A dynamic_cast to an ambiguous pointer will fail, while a static_cast returns as if nothing were wrong; this can be dangerous. Although dynamic_cast conversions are safer, dynamic_cast only works on pointers or references, and the run-time type check is an overhead.
static_cast<type> (expr)
Here, type specifies the target type of the cast, and expr is the expression being cast into the new type.
The static_cast operator is essentially a substitute for the original cast operator. It simply performs a non-polymorphic cast.

For example, the following casts an int value into a double.
// Use static_cast.
#include <iostream>
using namespace std;
int main()
{
int i;
for(i=0; i<10; i++)
cout << static_cast<double> (i) / 3 << " ";
return 0;
}
Source : Google

0 comments:

Post a Comment