[fpc-devel] suggestion: virtual method co-variance

Hans-Peter Diettrich DrDiettrich1 at aol.com
Wed Oct 15 04:21:04 CEST 2014


Sven Barth schrieb:

> At least at first sight there don't seem to be any real (technical) 
> reasons to not covariance for return values. Parameters would be a 
> different topic though...
> 
> Just so I get the idea right:
> 
> === code begin ===
> 
> type
>   TBar = class
>     function Test: TObject; virtual;
>   end;
> 
>   TFooBar = class(TBar)
>     function Test: TStrings; override;
>   end;
> 
> //...

I just wonder about the purpose and use of such refinement. Should the 
compiler relate on an more specific return type, based on the *static* 
type of an object reference? I'd use different names for specialized 
methods/properties instead.

OTOH it would be nice to have specialized lists without much coding, 
i.e. without writing getters (and setters) which only do typecasts of 
their results. Something like

type
   TBar = class
     property Test: TObject ...; virtual;
   end;

   TFooBar = class(TBar)
     property Test: TStrings; override;
   end;

Please note that this kind of override should not require to override 
the getters/setters, it only would enforce (static) type checks/casts, 
as doable at compile time.

But that smells like Generics, which already have their place in OPL...


Parameters would require different handling, because a single type 
mismatch would defer to the base class implementation, with possibly 
strange effects when this results in an bypass of the modified code in 
the overridden methods. That's another argument for my above suggestion, 
which should not only eliminate the need for overriding related methods, 
but should *disallow* explicit getter/setter overrides - so we were back 
again at generics?

DoDi




More information about the fpc-devel mailing list