Covariant return types in C + + class override methods
In C + +, as long as the original return type is a pointer or reference to a class, the new return type is a pointer or reference to the derived class, and the overridden method can change the return type. Such a type is called the covariant return type (covariant returns type).
Covariant (covariant), if it keeps the subtype ordinal relationship ≦. The order relationship is: Subtype ≦ base type.
Contravariant (contravariant), if it reverses the subtype order relationship.
parametric inversion: Precisely because of the need to comply with the Richter replacement law,parameter type declaration in a method must conform to the inverse (or constant), so that the subclass method can receive a larger range of parameters (processing power enhancement), and cannot be declared as covariant, the subclass method can receive a subset of the parameter types in the parent class (the processing power is weakened).
return value covariance: If the result type is contravariant, the processing power of the subclass method is weakened and does not conform to the Richter scale replacement.Therefore, the return value type declaration must conform to covariant (or unchanged)。 A truth in programming language is that a parent reference can point to a subclass instance such as
Large Basket Base B = Small basket New Child ()
It's like a big basket of parents that can put down a sub-class basket
Specific to covariant contravariance example
A function (B)
{
Return C
}
D ret = function (F);
As shown above, according to the theory of large basket-loaded small baskets
D can only be a parent of a or a, which is the return value covariance . Already has a small basket, you want to pretend he can only use big basket, can't use small basket that can become small to install small basket, therefore this small basket cannot support to become small, is small basket to covariant (big).
F must be a subclass of B or B, which is the parameter inversion . is to give you a big basket in there, you have to install only a small basket can be changed into, that is, put in the basket can be smaller, that is, large baskets to invert (small).
Covariant return types in C + + class override methods