Return Type Covariance

suggest change

Remarks

Covariance of a parameter or a return value for a virtual member function m is where its type T gets more specific in a derived class’ override of m. The type T then varies (variance) in specificity in the same way (co) as the classes providing m. C++ provides language support for covariant return types that are raw pointers or raw references – the covariance is for the pointee or referent type.

The C++ support is limited to return types because function return values are the only pure out-arguments in C++, and covariance is only type safe for a pure out-argument. Otherwise calling code could supply an object of less specific type than the receiving code expects. MIT professor Barbara Liskov investigated this and related variance type safety issues, and it’s now known as the Liskov Substitution Principle, or LSP.

The covariance support essentially helps to avoid downcasting and dynamic type checking.

Since smart pointers are of class type one cannot use the built-in support for covariance directly for smart pointer results, but one can define apparently covariant non-virtual smart pointer result wrapper functions for a covariant virtual function that produces raw pointers.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Return type covariance:
* Return Type Covariance

Table Of Contents
8 Arrays
11 Loops
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
105 Return type covariance
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype