[Gambas-user] Inheriting, wrapping and casting

Bruno Félix Rezende Ribeiro oitofelix at ...181...
Fri Apr 18 05:10:43 CEST 2014


Em Thu, 17 Apr 2014 21:13:41 +0200
Fabien Bodard <gambas.fr at ...626...> escreveu:

> Well ... I'm surely not good as you are but I didn't understand the
> meanning of castup or down... What is it for ?

Let me give you an abstract example.  Suppose we have the class
'SuperClass' which implements the function 'Frobnicate' that has the
following signature:

  Static Public Function Frobnicate(hSuperClass As SuperClass) \
    As SuperClass

Suppose now that we've extended our original class, and thus derived
the class 'SubClass', and let 'hSubClass' be any object thereof.
Suppose the function 'Frobnicate' was not overridden and that
'SuperClass.Frobnicate(hSubClass)' is generally not that useful because
the implicit identity casting doesn't generate a very meaningful
'SuperClass' object for the problem at hand.  However, we have a much
more interesting idea than the interpreter of how to map 'SubClass'
objects to meaningful and useful 'SuperClass' objects.  Here the
proposed special method '_castUp' comes in hand.  We add it to the code
of 'SubClass' in order to do the desired up-cast automatically:

  Static Public Function _castUp(hSubClass As SubClass) As SuperClass
    ' Do a magical conversion using arbitrary processing in accordance
    ' with our idea of a canonical map from 'SubClass' to 'SuperClass'.
  End

Now when the interpreter evaluates the expression
'SuperClass.Frobnicate(hSubClass)' it'll notice there is an up-cast
method and then it'll give this precedence over the implicit identity
casting.  Now we have a meaningful object to work with!

The '_castDown' special method works analogously but the other way
around.  The only major difference is that the interpreter doesn't have
a standard implicit identity cast in this direction and therefore raises
an error when one tries to use a 'SuperClass' object in a 'SubClass'
context.

The main point to emphasize here is that we are interested in
non-trivial castings.  Therefore, we need it both directions and
identity casts (the copy of common properties) doesn't suffice.


Hope it helps.
Happy Hacking!


-- 
 ,= ,-_-. =.  Bruno Félix Rezende Ribeiro (oitofelix) [0x28D618AF]
((_/)o o(\_)) There is no system but GNU;
 `-'(. .)`-'  GNU Linux-Libre is one of its official kernels;
     \_/      All software must be free as in freedom;
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 490 bytes
Desc: not available
URL: <http://lists.gambas-basic.org/pipermail/user/attachments/20140418/17b781e2/attachment.sig>


More information about the User mailing list