C++ virtual function return type

Bob picture Bob · Jan 12, 2011 · Viewed 48.5k times · Source

Is it possible for an inherited class to implement a virtual function with a different return type (not using a template as return)?

Answer

templatetypedef picture templatetypedef · Jan 12, 2011

In some cases, yes, it is legal for a derived class to override a virtual function using a different return type as long as the return type is covariant with the original return type. For example, consider the following:

class Base {
public:
    virtual ~Base() {}

    virtual Base* clone() const = 0;
};

class Derived: public Base {
public:
    virtual Derived* clone() const {
        return new Derived(*this);
    }
};

Here, Base defines a pure virtual function called clone that returns a Base *. In the derived implementation, this virtual function is overridden using a return type of Derived *. Although the return type is not the same as in the base, this is perfectly safe because any time you would write

Base* ptr = /* ... */
Base* clone = ptr->clone();

The call to clone() will always return a pointer to a Base object, since even if it returns a Derived*, this pointer is implicitly convertible to a Base* and the operation is well-defined.

More generally, a function's return type is never considered part of its signature. You can override a member function with any return type as long as the return type is covariant.