C++ : Covariant return type without pointer

后端 未结 2 1641
长发绾君心
长发绾君心 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:51

    The idea of a covariant return type is a polymorpihc return type. And in C++, you can't have run time polymorphism without pointers or references. Let's ignore for a second most of the hardships, and pretend it's possible. Here is my code that handles things by your Parent interface:

    void bar(Parent * p) {
      auto o = p->foo();
    }
    

    What is o? Well, it's Parent of course. Says so in Parent::foo's return type. But what if that p is pointing at a Child? The deduced type of o is still Parent, so at best I get a sliced object. No polymorphic behavior, so the whole exercise is pointless.

    At worst, and quite likely, I get undefined behavior.

    That's why co-variant return types have to be pointers or references.

提交回复
热议问题