C++ Inheritance: Derived class pointer to a Base class invokes Derived class method

前端 未结 6 1785
眼角桃花
眼角桃花 2021-01-25 20:28

I am learning C++ inheritance, so I tried this code by creating a Base class dynamically and made a downcast to its Derived class (obviously its not valid to downcast) in order

6条回答
  •  深忆病人
    2021-01-25 21:05

    Polymorphism doesn't work like that. Interestingly your C-style cast from parent* to child* works because the classes don't have a v-table or anything else other than the function who. So the address of who must be the same as the address of the class itself.

    parent *p = (parent*)new child();

    will make more sense, but even then, p->who() would only call the child class function if you mark the function who virtual in the parent class, which you haven't done.

提交回复
热议问题