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

Sven Barth pascaldragon at googlemail.com
Tue Oct 14 14:21:56 CEST 2014


Am 14.10.2014 12:41 schrieb "Marco van de Voort" <marcov at stack.nl>:
>
>
> I recently had to dive a bit into C++ again, and reconnected with a
feature
> I liked at first sight, the C++ covariance of virtual methods (changing
the
> return type of a overriden method to a descendant of the original type).
> Googling a bit it seems that some languages(C#) also seem to allow this
for
> parameters.  (not just return types)
>
> I suddenly wondered why it was never proposed or talked about  for FPC,
> since it seems such a nice feature.  Is there something particularly wrong
> with it?

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;

//...

var
  b: TBar;
  f: TFooBar;
  s: TStrings;
begin
  f := TFooBar.Create;
  b := f;
  // this would work
  s := f.Test;
  // but this not
  s := b.Test;
end.

=== code end ===

Would this be the correct equivalent in Object Pascal?

Regards,
Sven
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-devel/attachments/20141014/f9432a11/attachment.html>


More information about the fpc-devel mailing list