Covariant returns?

Chris Heath cheath@umich.edu
Tue Mar 7 06:51:00 GMT 2000


> > So even though C::This is called, the return value must be converted
> > to B*, when calling the virtual function for a B*.
> 
> The type returned is a pointer.  Specifically the this pointer for C.
> Now I'm not too familiar with the internals of the compiler nor the
> implementation specifics of c++ in gcc.  But I still don't see why the
> value of C::this would be different no matter what the return type
> for the method is.

Yes, C::This is called 3 times, and each time it returns a pointer to C,
namely &cl.  But the problem is that it is not properly converted to a
B*.

As demonstrated in the line 
  B* b=&cl;
the conversion from a C* to a B* actually changes the value of the
pointer:  &cl is effff9b0 but b is effff9b4 on my system.  This is the
difference between a static_cast and an (unsafe) reinterpret_cast.

When calling B->This, the C* pointer is not being static_cast to a B*.  It
is simply being reinterpreted as a B*, which is a bug.

Looking back in the archives, I noticed that Martin has been discussing a
general mechanism for handling this sort of situation (see gcc mailing
list, Feb 20 2000, Functions with multiple entry points).  In this
particular case, C::This would have two entry-points, one if the
return should be converted to B* and one if the return is A* or C*.

However, until some such mechanism is implemented, I think the compiler
should produce an error message rather than incorrect code. 

Chris



More information about the Gcc mailing list