1

Possible Duplicate:
c-style cast vs reinterpret_cast

What is the difference between:

A* pA = new B;

B* p1 = (B*)pA;
B* p2 = reinterpret_cast<B*>(pA);

Are they both identical ways of doing the same thing? Is there any reason to choose one over the other? Should the "C style" cast be avoided in C++ code?

Community
  • 1
  • 1
user974967
  • 2,928
  • 10
  • 28
  • 45

1 Answers1

8

A C-style cast is equivalent to the first of the following that succeeds:

  • a const_cast
  • a static_cast
  • a static_cast followed by const_cast
  • a reinterpret_cast
  • a reinterpret_cast followed by const_cast

So in certain situations, a C-style cast will have the same effect as reinterpret_cast but they are not equivalent. Since a C-style cast is basically a "oh, just cast it however you can" cast, it's better to prefer the more specific casts.

For your example, it is preferable to use a static_cast since you know the actual type of the derived object. When you don't, use dynamic_cast.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324