[fpc-pascal] casting back a pointer to original type
Michael Van Canneyt
michael at freepascal.org
Sat May 29 18:11:38 CEST 2010
On Sat, 29 May 2010, spir ☣ wrote:
> Say I store class instances of various types in a TFPList. All happen to be descendants of same superclass C and each one has a specific method "text". When retrieving and writing an element, if they were all direct instances of C, I would do something like:
> 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. Which is wrong, indeed.
> So, I must cast elements back to their own type; but I have no idea how to do this. Doesn't the compiler store this information? After all, when an element is put into the list, its type is known. Is there a reason why retrieving an element does not cast it back to its original type automatically? Should I store element types manually in a parallel list?
> There must be a way to solve this issue, I guess...
There are 2
1. Make all descendents descendent of a super class that has a text
2. Make the "text" property published, and use RTTI to get/set it.
> 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?
It depends on what you want to achieve. If you make it a static method, then
the compiler will emit a warning "function Text hides method of parent
class" (or something like it)
If you make it virtual, then you must explicitly add "override" to
override the implementation of the method.
More information about the fpc-pascal