I recently encountered a strange bit of behavior with the C++ dynamic cast in CodeWarrior 8.3, in some legacy code that had been morphed in strange ways over the years.
Here is the setup for an example. Let's start by defining a class and two subclasses:
class Base { ... };
class DerivedX : public Base { ... };
class DerivedY : public Base { ... };
Now, the following is not the way you'd normally use a dynamic cast in C++ code, but due to the quirky history of this particular body of old code, it has some strange constructs like the one here. It was doing a test of the object type in this fashion, in many places:
void foo(Base* obj)
{
DerivedX* test = (DerivedX*) obj;
if (dynamic_cast<DerivedX*>(test) != NULL)
{
std::cout << "obj is in fact an X" << std::endl;
}
}
The problem is that CodeWarrior 8.3 PPC optimizes this to a static cast: the dynamic cast result is the original pointer, since the cast is from/to the same type. The result is that if "obj" is pointing to a DerivedY object, the dynamic cast to DerivedX* will succeed anyway, resulting in a dangerous pointer to the wrong type; essentially, a static cast to the wrong type.
Surely, this is a bug in the compiler, since it is not dynamically checking the type. However, you can easily understand why the optimization makes some sense at first blush, and how it highlights the badness of the code as written, however legal it may be. The code has already statically declared the pointer "test" to be of a certain type (DerivedX*), so why on earth is it performing a dynamic cast to that same type?! It has already declared the "actual" type. The dynamic cast ought to sometimes return null (when "obj" points to a DerivedY, or is null itself), so the earlier C cast to initialize "test" is clearly dangerous, with "test" being a bad pointer when it points to a DerivedY.
(PS--the following is the typical corrected version of the code.)
void foo(Base* obj)
{
DerivedX* test = dynamic_cast<DerivedX*>(obj);
if (test != NULL)
{
std::cout << "obj is in fact an X" << std::endl;
}
}
[35] Google: "http://www.bombaydigital.com/arenared/2005/9/13/1"
[16] Google: "dynamic cast"
[6] http://blogsearch.google.com/blogsearch?hl=en&q=c%2B%2B&btnG...
[3] Google: "c++ dynamic cast"
[1] http://search.msn.co.za/results.aspx?q=dynamic_cast&FORM=QBR...
[1] Google: "c++ dynamic pointer"
[1] Google: "how to cast in C++"
[1] Google: "dynamic cast c++ -virtual"
[1] Google: "c++ cast static dynamic"
[1] http://search.blogger.com/?q=C%2B%2B&btnG=Search+Blogs&hl=en...