Search code examples
c++pointersdynamic-casttypecasting-operator

simple check for dynamic_cast c++


I do a dynamic_cast and want to check if the cast succeeds.

I am doing a basic null pointer check now. It like this:

A *temp_ptr = dynamic_cast<A *>(obj_ptr);
if( (temp_ptr) && (temp_ptr->some_function()))
{
      // do something if the function returns true
}
else
{
      // cast failed or function returns false
      // continue with normal execution
}

Is this fine or do I need to use assert ? All I care about is that particular function. Is there any other check that I should use ?

Would it pass a code review ?


Solution

  • The check of the results of the dynamic_cast protect the code from doing things incorrectly. An assert protects the program from programmers writing things incorrectly.

    Whether you should assert depends on whether it is a mistake for an object to not be of the target type of your dynamic_cast. If coming into this code you expect a mix of objects, some of which are and some of which are not of type A, then an assert would fire for legitimate usage. If every object at this point is expected to be of type A and an object not of that type indicates a programming error, then an assert makes sense, at least in debug builds.