Return Type

Covariant Return Type

First heard from Ross Evans in CS247.

They can be used for Function Overrides, where we have different return types to achieve some Polymorphism.

However, covariant return types must be pointers or references.

This doesn’t work for example, because the return type is different

class Shape {
public:
    virtual double getArea() override { return 0.0; }
};
 
class Derived : public Base {
public:
    float getArea() override { return 1.0; } // error, different return types
};

But this works, because Derived* is a child of a Base*

class Base {
public:
    virtual Base* clone() override { return new Base(this); }
};
 
class Derived : public Base {
public:
    Derived* clone() override { return new Derived(this); }
};
 
 
// You can then do this without the compiler complaining
Derived* d = new Derived{};
Derived* d2 = d->clone();

Links