Covariant return type

Stewart Gordon smjg_1998 at yahoo.com
Thu Mar 29 07:13:12 PDT 2007


"Aarti_pl" <aarti at interia.pl> wrote in message 
news:etu6qm$2251$1 at digitalmars.com...
>
> Jarrett Billingsley napisał(a):
>> "Aarti_pl" <aarti at interia.pl> wrote in message 
>> news:ettjqu$14jb$1 at digitalmars.com...
>>> Hello!
>>>
>>> Shouldn't code below work?:
>>>
>>> //-------------------------------------------
>>>
>>> abstract class Storage {
>>>     Storage get() {
>>>         return this;
>>>     }
>>> }
>>>
>>> class SpecificStorage : Storage {
>>>     void print() {}
>>> }
>>>
>>> void main() {
>>>     SpecificStorage s = (new SpecificStorage).get();
>>>     s.print;
>>> }
<snip>
>>> But my intuition about that would be that "this" pointer from method get 
>>> from Storage class will point to "SpecificStorage" when there is 
>>> instantiated SpecificStorage. But it looks that in fact this points to 
>>> "Storage".
<snip>
> Yes, but in fact I don't want to loose type information and upcast to 
> Storage. I just want to return 'this' as it is when return is invoked.

That's exactly what's happening.  You appear to be confusing objects with 
object references.

The object returned is a SpecificStorage, but the object reference is still 
of type Storage, because that's what the method returns.  Before you can 
assign the reference to a variable of type SpecificStorage, you have to use 
a cast to make the object reference of type SpecificStorage.

> Such a behavior seems a little bit nonsense when there is covariance 
> return type feature in programming language. To get covariance I have many 
> time reimplement same code in every inherited class just to trigger proper 
> behaviour.
<snip>

Your example appears contrived - in a real application, you likely wouldn't 
have a method that simply returns this, and continues to do so for every 
subclass.  You'd just use the object reference directly.  If you were to 
override it to do something different for some classes, then they need not 
even return an object of the same specific class as that in which it is 
called.

Moreover, there may be a generic programming use case for such things _not_ 
being implicitly covariant.

Stewart. 



More information about the Digitalmars-d-learn mailing list