When is C++ covariance the best solution?

后端 未结 6 708
温柔的废话
温柔的废话 2020-12-05 23:00

This question was asked here a few hours ago and made me realise that I have never actually used covariant return types in my own code. For those not sure what covariance is

6条回答
  •  感情败类
    2020-12-05 23:34

    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).

提交回复
热议问题