Same same: Covariant return types.

In this post, I want to talk about a specific feature. To set the table, it has to do with the return type of virtual functions. The compiler usually enforces that the return type of an override method match exactly the type of the base method declaration. However, there is a little leeway, with covariant return types. This is an interesting feature in C++ which isn’t supported in C#. In a nutshell, it allows the overriding method to change the return type, as long as it is a covariant return type. For example:

class Y {};
class Z : public Y {};

struct A {
   virtual Y* foo() { return new Y(); }
};
struct B : public A {
   Z* foo() { return new Z(); } // legal code. Notice the 
                                // change of return type. 
};

This follows the Liskov Substitution Principle (LSP) very nicely, since class Z IS A class A and can be substituted as such. The standard explains this in section [class.virtual / 10.3 ] paragraph 7. This is where the conditions placed on using covariant return types are outlined:

Continue readingSame same: Covariant return types.