How do I cast a parent class as the child class

后端 未结 8 1929
深忆病人
深忆病人 2020-12-29 19:46

It\'s been a while since I have had to write C++ code and I\'m feeling kind of stupid. I\'ve written code that is similar to, but is not exactly, the code b

相关标签:
8条回答
  • 2020-12-29 20:41

    I think the problem isn't with how your trying to do the cast, but with why you want to cast in the first place. The code makes no sense -- even if it was syntaxically valid. You;re trying to cast a "fruit" into an "apple" in a context where it's easy to prove that you don't actually have an apple. Dynamic casts and similar are only useful when you have a pointer to a "fruit" that you have reasons to thing is also an "apple".

    0 讨论(0)
  • 2020-12-29 20:43

    Refer to the code snippet below:

    Child* c = dynamic_cast<Child*>(parentObject);
    

    where, parentObject is of type Parent*

    Ensure, that the "parentObject" is actually of "Child" type, otherwise undefined-behavior.

    Refer for More Info

    0 讨论(0)
提交回复
热议问题