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

spir ☣ denis.spir at gmail.com
Sun May 30 12:37:19 CEST 2010


On Sat, 29 May 2010 16:54:44 -0700
Andrew Hall <andrew.hall at shaw.ca> wrote:

> On 29 May 10, at 15:26 , spir ☣ wrote:
> > 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.
> 
> David is not suggesting you have two methods with different names - his example is demonstrating the different behaviour of static and virtual methods. Calling a static method is determined at compile time - the compiler must use the actual class of your variable (or cast) - so your descendent methods will never be called.  This is what is happening to you at the moment - only your base class Text method is called.  Calling a virtual method is determined at runtime based upon the actual class held by the variable (cast) - it seems this is exactly what you need.  Set your base class Text method as virtual, and each descendent class Text method as override - your code should then function as you require...
> 
>    element := C(list[index]);
>    text := element.text;
> 
> if the pointer in list[index] is C1, C1.Text will be called.
> 
> Regards,  
> Andrew.

Thank you very much, David & Andre. Sorry, David, I had not understood the intent of your example post. Your comment and Andre's clarified everything.
OK, I lurred myself by taking words too literally. I thought "virtual" meant unimplemented, to be implemented in sub-classes. So, for me, this could not apply to my case, since supaer-classes also need the method to be implemented.
Just did a fast trial: works fine.

Denis
________________________________

vit esse estrany ☣

spir.wikidot.com



More information about the fpc-pascal mailing list