Need For Covariant Argument Types?
In many strictly typed languages (with the notable exception of Eiffel, see below), subclassing must allow for substitution. That is, a child class can always stand in for a parent class. This places restrictions on the sorts of relationships that subclassing can represent. In particular, it means that arguments to member functions can only be contravariant and return types can only be covariant, as explained in previous section.
This creates problems in some situations, where argument types should be covariant to model real-life requirements. Suppose you have a class representing a person. A person can see the doctor, so this class might have a method virtual void Person::see(Doctor d)
. Now suppose you want to make a subclass of the Person
class, Child
. That is, a Child
is a Person
. One might then like to make a subclass of Doctor
, Pediatrician
. If children only visit pediatricians, we would like to enforce that in the type system. However, a naive implementation fails: because a Child
is a Person
, Child::see(d)
must take any Doctor
, not just a Pediatrician
.
We could try moving the see
method to the Doctor
class hierarchy, but we would have the same problem: If a Doctor
could see a Person
and a Child
is a Person
, then there is still no way to enforce that a Child
must see a Pediatrician
and that a Person
who is not a Child
cannot see a Pediatrician
and must see another Doctor
.
In this case, the visitor pattern could be used to enforce this relationship. Another way to solve the problems, in C++, is using generic programming (see below).
Read more about this topic: Covariance And Contravariance (computer Science)
Famous quotes containing the word argument:
“English! they are barbarians; they dont believe in the great God. I told him, Excuse me, Sir. We do believe in God, and in Jesus Christ too. Um, says he, and in the Pope? No. And why? This was a puzzling question in these circumstances.... I thought I would try a method of my own, and very gravely replied, Because we are too far off. A very new argument against the universal infallibility of the Pope.”
—James Boswell (17401795)