2 C style (reinterpretive) casting

The C-style cast operator is very flexible, and very dangerous. This is because it can do just about any kind of casting, whether it makes sense or not. Observe the following code:

class A
{
  // blah blah blah
};

class B
{
  // yada yada yada
};

void test(void)
{
  A *pA;
  B *pB;

  pA = (A*)pB;
}

This code actually compiles without any problem! It does not make any sense, as classes A and B are completely unrelated. Note that we can rewrite the assignment statement as follows:

pA = reinterpret_cast<A*> (pB);

The cast operator reinterpret_cast is a C++ feature that is not found in C. However, its meaning is the same as the C cast operator in the original code.

You should avoid the use of the reinterpret_cast operator as it is very dangerous.


Copyright © 2006-10-12 by Tak Auyeung