От: | cppguard | ||
Дата: | 06.03.23 08:46 | ||
Оценка: |
Covariance refers to the ability to substitute a subtype for a supertype in a way that preserves the directionality of subtyping. This means that if we have a type hierarchy A <: B, where A is a subtype of B, we can use an object of type A wherever an object of type B is expected. In other words, if we have a function that takes an argument of type B, we can pass in an object of type A as the argument and it will work correctly. This is because A is a subtype of B, and therefore, A is guaranteed to have all of the properties and methods of B, as well as any additional properties and methods specific to A.
Contravariance, on the other hand, is the ability to substitute a supertype for a subtype in a way that preserves the directionality of subtyping. This means that if we have a type hierarchy A <: B, where A is a subtype of B, we can use an object of type B wherever an object of type A is expected. In other words, if we have a function that takes an argument of type A, we can pass in an object of type B as the argument and it will work correctly. This is because B is a supertype of A, and therefore, B is guaranteed to have all of the properties and methods of A, as well as any additional properties and methods specific to B.