dynamic_cast<> fails but static_cast<> works
c++, dynamic-cast
Solution
`dynamic_cast` will "not work" in two instances:
You have somehow compiled your code without RTTI. Fix your compiler settings.
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`.
Problem
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