When is C++ covariance the best solution?

The canonical example is a .clone()/.copy() method. So you can always do

 obj = obj->copy();

regardless what obj’s type is.

Edit: This clone method would be defined in the Object base class (as it actually is in Java). So if clone wasn’t covariant, you would either have to cast, or would be restricted to methods of the root base class (which would have only very few methods, compared the class of the source object of the copy).

Leave a Comment