c++ gurus: reinterpret_cast vs. static_cast

Over the last couple days, I’ve been reading up on the various casting operators in C++. I understand dynamic_cast and const_cast, but for the life of me, I can’t tell the difference between reinterpret_cast and static_cast. Any light to shed here?

Here’s a good article on the subject:

http://www.coding-zone.co.uk/cpp/articles/050101casting.shtml

It isn’t clear what you’re having difficulties with, but this clears it up for me:

http://www.hlrs.de/organization/tsc/services/tools/docu/kcc/UserGuide/chapter_9.html

In section 9.3, and in particular, the section after the description of the casts.

A static_cast is like a dynamic_cast, except it would allow this:

Assuming Base class A, derived class B (derived from A)

int main()
{
A* foo;
B* bar;

foo = new A;

bar = dynamic_cast<B*>(foo); // falls at compile time (and certainly at run time)

bar = static_cast<B*>(foo); // works, although may prove to be problematic as the object is used

// (conversely, obviously, upcasting, that is casting a point of type B to type A is legal and works with a dynamic_cast).

}

Use of static_cast isn’t considered a good thing; use a dynamic_cast instead.

A reinterpret_cast damn near always compiles. It is closest to a oldstyle C cast, and its used when you e.g. really, really need to store a point as a long, and is a polite way of saying that this is tricky and suspicious code.

The documentation states that a reinterpret_cast cannot be used when one of the other casts will do the job, that is, one cannot use a reinterpret_cast when a dynamic_cast will work. That does not match my memory, but I really used reinterpret_casts, and only under MSVC, and perhaps MS was not as conscientious of implementing that feature as they should have been.

Huh? A dynamic_cast can be used to go from a base pointer to a derived pointer. That’s pretty much what it’s for. The base class must have some virtual functions in it so that RTTI is present; dynamic_cast is all about using such information. And going from a derived pointer to a base pointer doesn’t require a cast at all.

It doesn’t require an explicit cast, but there is casting going on in that scenario.