[fpc-pascal] Type-casting a class variable

Martin Frb lazarus at mfriebe.de
Wed May 1 20:21:43 CEST 2024


On 01/05/2024 16:28, Adriaan van Os via fpc-pascal wrote:
> Suppose I have a
>
>     var myClass: TClass
>
> and (for example) a
>
>     class function TWindow.CreateNewWindow( ....)
>
> Now I want to call CreateNewWindow for var myClass. Of course, 
> depending on the class, CreateNewWindow will behave different. 
> Type-casting myClass to TWindow crashes (in my setup). And even if it 
> worked, wouldn't it loose the class information ?
>

Silly question, but did you assign the value to the variable?

myClass := TWindow;
TWindow(myClass).CreateNewWindow;

The cast is not always needed.

If you have

var myClass: TMyClass;

with
   TMyClass = class
    class  procedure  CreateNewWindow; virtual
   end;

And any inherited class correctly overrides this, then you don't need 
the typecast.


More information about the fpc-pascal mailing list