In my project I have a scenario like suppose:
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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With