Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic_cast<> fails but static_cast<> works

In my project I have a scenario like suppose:

  • 1) BaseClass is an interface which derives from a parent class IFlow
  • 2) ChildClass derives from it ie from Base class
  • 3) In childClass Init function I am using dynamic_cast to cast the objet of IFlow to BaseClass which is as shown below:

    void ChildClass::init()
    {    
        IFlow* pFlow = someMethod(); //it returns the IFlow object pointer
    
        //this works for static cast but fails for dynamic cast    
        BaseClass *base =  dynamic_cast<BaseClass*>(pFlow) ;
    } 
    

In the above code the 2nd line of dynamic _cast returns zero but if the dynamic_cast is changed to static_cast then the code works as expected . Please advice

like image 860
user1495421 Avatar asked Dec 26 '22 22:12

user1495421


1 Answers

dynamic_cast will "not work" in two instances:

  1. You have somehow compiled your code without RTTI. Fix your compiler settings.

  2. The entire purpose of dynamic_cast is to ensure that the cast actually works. Casting from child to parent always works because every child of some type is guaranteed to be that type (the whole "all dogs are animals, but not all animals are dogs" thing). Casting from a parent to a child can fail if the object is not actually that child type. dynamic_cast will return a null pointer if the IFlow you give it is not actually a BaseClass.

    Furthermore, your static_cast does not work. It simply returns a value. A value which, if you ever use it, results in undefined behavior. So it only "works" in the sense that it returned a value you could attempt to use.

So one of these two things happened. Which one is up to you to find, since you didn't give us the implementation of someMethod.

like image 99
Nicol Bolas Avatar answered Jan 08 '23 09:01

Nicol Bolas