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.
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