[fpc-pascal] Classes and class methods

Mark Morgan Lloyd markMLl.fpc-pascal at telemetry.co.uk
Wed Feb 9 12:41:41 CET 2011


Marco van de Voort wrote:
> In our previous episode, Mark Morgan Lloyd said:
>> Is it possible to put a class (not an instance) in a variable or array 
>> element, and to use this to call a class method?
>>
>> I'm defining a hierarchy of classes and it would be convenient if it 
>> were possible to register the fact that a class had a particular 
>> subclass, such that the information was available before instantiation.
>>
>> I'm assuming that the code that inspects the array has imported all 
>> units so is aware of the relevant class declarations, but I am still 
>> having problems with calling class methods and/or casting to a class (as 
>> distinct from an instance).
> 
> Afaik this route you can only call static methods of the basetype of the
> class-type.
> 
> So if it is   
>      
>      A= class
>           end;
>      b=class(a)
>           end;
>      c=class(b);
> 
>      TClasstype  = class of  B;
> 
> 
> var x : TClasstype;
> 
> begin
>   x:=C;
> 
>   x.staticmethod
> 
> then staticmethod must be visible in B. It doesn't matter which descendant
> of B you assign to X.
> 
> This is logical, since static methods are entirely compiletime, and the
> compiler can't know what type will be runtime assigned.

Thanks Marco, I was beginning to suspect that I was hitting limitations 
and that what I was trying to do might be ill-advised.

I'm finding virtual class methods useful when I'm able to refer directly 
to a class, rather than going via a reference to a class.

-- 
Mark Morgan Lloyd
markMLl .AT. telemetry.co .DOT. uk

[Opinions above are the author's, not those of his employers or colleagues]



More information about the fpc-pascal mailing list