Passing null into dynamic_cast<>

Sep 29, 2004
18,656
68
91
Obviously I would never do this, but for the love of code maintenance I have to ask. Assume you have the following code Where Foo is a child of base class BaseClass

-----------------

Foo* foo = null;

if( dynamic_cast<BaseClass>( foo ) )
return dynamic_cast<BaseClass>( foo );
else
// print error message


-----------------

My assumption is that dyamic_cast<> would die a fiery death so that else function is pointless.

Since this is a static system that I am dealing with, foo is defined by performing a look up. The else branch always occurs or never occurs. Which means that nothing bad has ever happened in the deployed environment. But code like this really angers me.

back to the question: What would happen in the code I gave above?


--------------
MISC:
The code also uses upper camel case for classes and methods. I appreciate that along with the over use of extern.
 

Venix

Golden Member
Aug 22, 2002
1,084
3
81
dynamic_cast just returns a null pointer if you give it a null pointer. That code (assuming you meant dynamic_cast<BaseClass> to be dynamic_cast<BaseClass*> ) will just always run the else case.

Do you know the intended purpose of the code? dynamic_cast to a base class will always succeed, so there seems to be no point. If the purpose is to verify that Foo is derived from BaseClass, that's one of the worst possible ways to do it. Even a simple static_cast<BaseClass*>((Foo*)0) would cause an infinitely more useful compile time error.