A virtual function\'s return type should be the same type that is in base class, or covariant. But why do we have this restriction?
The answer is very similar to the one given for "Why can't I assign a vector
The ability to modify the return type would lead to a hole in the type safety of the language (see the answer from @GManNickG for a specific example) when dealing with polymorphic types.
There is one fairly common situation when affecting the return type would be ideal: when returning a polymorphic pointer from a virtual method of a base type. For example,
class Base {
public:
virtual Base* parent() = 0;
};
class Child : public Base {
public:
Base* parent() override
{
return parent_;
}
private:
Parent* parent_; // Assume `Parent` type exists.
};
Here we lost the type information that Child
knows about it's parent_
member. This leads to lots of casting, even though the type was at one point well defined. We can solve this using the Curiously Recurring Template Parameter (CRTP) idiom,
template
class Base {
public:
virtual ParentType* parent()
{
return parent_;
}
private:
ParentType* parent_;
};
class Child : public Base {
};