C++ : Covariant return type without pointer

后端 未结 2 1671
长发绾君心
长发绾君心 2021-01-14 07:10

I create two simple classes by inheritance, and I add a virtual function and the override in the child class.

class P         


        
2条回答
  •  半阙折子戏
    2021-01-14 07:55

    It is because the derived type would return a derived instance but the caller would be expecting a parent, this is different from when using pointers, in the pointer case the derived pointer can just slide into the space reserved for the parent pointer but the same is not true when talking about actual instances. You also have the problem that the derived method would return a derived instance but a caller using a parent pointer would have no idea about that and thus probably only destroy the parent parts.

    you can find this helpful

提交回复
热议问题