[fpc-pascal] casting back a pointer to original type

spir ☣ denis.spir at gmail.com
Sun May 30 00:26:54 CEST 2010


On Sat, 29 May 2010 10:46:45 -0700
David Emerson <dle3ab at angelbase.com> wrote:

> >     element := C(list[index]);   // casting back
> >     text := element.text;
> > I cannot do that, even if elements all are *indirect* instances of C, because
> > this calls C.text instead of the element's own proper text method.  
> 
> If you use virtual methods then C.text should call the descendant's method. This 
> is what polymorphism, the most powerful concept in object oriented programming, 
> is all about.
> 
> > Side-question: it seems, when subclassing, that methods with same name and
> > same parameters do not need any modifier keyword (such as "override"
> > or "overload"). Eg I can have  
> >     function text;
> > in both a superclass C0 and a subclass C1 work as expected. Correct?  
> 
> This is likely your problem. If you are not using virtual methods then you are 
> not going to get polymorphism.

I cannot do that. C0 (and all classes) instances need a text method. I also cannot have 2 methods (one static, one virtual) with different names. It's a basic feature, always called with the same name. Like getItem for a hierarchy of collections: every collection must have it, and always under the same name, so that any client can rely on it.
I'll have to find a workaround. As of now, the only solution I can imagine (but it's really really stupid) is to store somewhere, in a // list, the actual types of all items recorded in a TFPList.
But I find this incredible... I must be overlooking something basic; how do you use TFPList, if when reading back stored items their types are lost in ether? TFPList is precisely intended to record class instances, meanings all kinds of stuff descending from TObject, or am I wrong on this? Is there another kind of (pointed) sequential collection able to store class instances without losing its items' types?
Another solution may be to store the type as an additional attribute of items themselves, before they are put into a collection. But since Pascal is static, this cannot be done "live" at runtime; meaning *all* items in the system must have this attribute. But I could then probably do something like:
   // the looked up item is list[index]
   // first read (a reference to) its type on the item itself
   typ := list[index].type;
   // now I can read and cast it
   item := typ(list[index]);


Denis
________________________________

vit esse estrany ☣

spir.wikidot.com



More information about the fpc-pascal mailing list