2

Is there any purpose to using dynamic_cast when the return value isn't checked for NULL? If I'm looking at a code base, and the null check it omitted from the return value, might it have been just as well to use static_cast?

A *a = dynamic_cast<A *>(b);
foo(*a);   //might as well have used a static_cast

I've read all that Google affords on the matter, and it seems that checking for null is the only reason, but I've yet to see anyone come out and say "dynamic_cast without a null check is a waste of cycles (and a possible bloating of the code with RTTI)."

Edit: It's been put to me that if there's virtual inheritance between the types, that static_cast would fail where dynamic_cast would not. In my case, that's not the case.

Opux
  • 702
  • 1
  • 10
  • 30
  • _If new_type is a pointer or reference to some class D and the type of expression is a pointer or reference to its non-virtual base B, static_cast performs a downcast. **This downcast is ill-formed** if B is ambiguous, inaccessible, **or virtual base (or a base of a virtual base) of D. Such static_cast makes no runtime checks to ensure that the object's runtime type is actually D**, and may only be used safely if this precondition is guaranteed by other means, such as when implementing static polymorphism._ [Source](http://en.cppreference.com/w/cpp/language/static_cast) – Algirdas Preidžius Mar 28 '17 at 19:10

1 Answers1

3

Is there any purpose to using dynamic_cast when the return value isn't checked for NULL?

You may not check for nullptr if you are sure that class instance is that type by different matter. Why not to use static_cast in this case? You may not be able to use static_cast when virtual inheritance is involved. Details can be found in answers for this question: Why can't static_cast be used to down-cast when virtual inheritance is involved?

Community
  • 1
  • 1
Slava
  • 43,454
  • 1
  • 47
  • 90
  • I see. So if there was a virtual relationship between `A` and `B`, then `static_cast` would be a problem, and `dynamic_cast` would be justifiable, right? In my case, there is not. – Opux Mar 28 '17 at 19:19