I create two simple classes by inheritance, and I add a virtual function and the override in the child class.
class P
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.