#include <iostream> class Base { }; class Derived : public Base { }; int main() { Base* bptr = new Derived(); Derived* dptr = static_cast<Derived*>(bptr); std::cout << dptr << std::endl; } In the above code, I should be using dynamic_cast but am using static_cast incorrectly. static_cast should never be used while downcasting, since compiler has no way to determine we are doing cast correctly.
Why isn't this a compile error? I am using gcc 4.9.2. Do you guys think this is a bug in the compiler, or does C++ standards allow such code ?
Edit: Thanks for the responses. Actually, Base class above is polymorphic, i.e. it has virtual functions, but I left them out for this example. I should have thrown in a virtual destructor in the Base to make it clear that it was polymorphic – my bad.
static_castfromBase*toDerived*, but you are correct that it will not perform any type-checking. It is still useful though, if you know through some other way that that pointer does actually point to aDerviedobject. If theBase*didn't actually point to aDerived*then any dereferencing of theDerived*resulting from astatic_castwould invoke undefined behaviour.static_castis for; after all, conversions towards base class pointers/references are done implicitly.