devxlogo

Pointers to Member Contravariance

Pointers to Member Contravariance

A pointer to member of a base class can be converted to a pointer to a corresponding member of its derived class. The opposite, however, is illegal: you cannot convert a pointer to member of a derived class to a pointer to member of its base class. This rule is called “pointer to member contravariance.”

The contravariance rule seems inverted compared to the rule for ordinary pointers to objects (i.e., you can convert a pointer of a derived to a pointer its base but not vice versa). This inversion is necessary because a derived class has at least the members it inherits from its base class, and therefore any pointer to member of a base class can be mapped to its corresponding member in a derived class. The opposite, of course, may not be true because a derived class can have additional members.

devx-admin

Share the Post: