Wednesday, January 31, 2007
Why bother with C++ explicit cast
C++ explicit cast are static_cast, const_cast, reinterpret_cast, and dynamic_cast.
int i = 5;
float j;
j = (float)i; /* C cast */
j = float(i); /* C++ generic cast */
j = static_cast(i); /* C++ explicit cast */
The reasons to use C++ explicit cast are clarity and correctness. It's a safty net as show in the following examples.
int i = 5;
float *pj;
pj = (float *)i; /* legal */
pj = (float *)(i); /* legal */
pj = static_cast(i); /* ILLEGAL */
pj = reinterpret_cast(i); /* legal */
When you got a bug in your code and you suspect it's caused by casting, you'll generally look at the reinterpret_cast before static_cast, so it can help reduce the debugging effort too.
int i = 5;
float j;
j = (float)i; /* C cast */
j = float(i); /* C++ generic cast */
j = static_cast
The reasons to use C++ explicit cast are clarity and correctness. It's a safty net as show in the following examples.
int i = 5;
float *pj;
pj = (float *)i; /* legal */
pj = (float *)(i); /* legal */
pj = static_cast
pj = reinterpret_cast
When you got a bug in your code and you suspect it's caused by casting, you'll generally look at the reinterpret_cast before static_cast, so it can help reduce the debugging effort too.