[fpc-devel] Language extension: absolute for classes
Michalis Kamburelis
michalis at camelot.homedns.org
Sun Oct 1 23:01:57 CEST 2006
Micha Nelissen wrote:
> Michalis Kamburelis wrote:
>> All you want is just to cover in class B identifier "Field" of class A.
>> So you should make "Field" a dummy function in class A (that just
>> returns a field value), and then you can redefine function name in
>> descendant classes. See the example below. Within the scope of class B
>> the "Field" function will return class G.
>
> This is a smart hack, at best. It's abuse of function syntax IMHO (as if
> they were fields). Second, you cannot assign to a function.
>
> If the functions were inline, it could be as optimal, I agree; then you
> have essentially localized the typecast to one place.
>
> I just want to tell the compiler what I can guarantee, but what it
> cannot automatically infer.
>
It can be done for properties too. And I agree, this can be considered
an "abuse" but not of the function syntax. It's an abuse of the rule
that you can always hide identifiers of parent class in a subclass.
Virtual methods are a typical clean solution to similar problems, but in
this case you want to change the method/property interface so we're left
with this unclean solution.
BTW That's why I agree with the cleaner approach of "overriding
properties" later in this thread.
Example below shows the same trick working for properties. Here "Field"
is a read/write property.
-----------
{$mode objfpc}
type
TF = class
end;
TG = class(TF)
end;
TA = class
private
FField: TF;
protected
property Field: TF read FField write FField;
end;
TB = class(TA)
private
function GetField: TG;
procedure SetField(Value: TG);
protected
property Field: TG read GetField write SetField;
end;
function TB.GetField: TG;
begin
Result := (inherited Field) as TG;
end;
procedure TB.SetField(Value: TG);
begin
(inherited Field) := Value;
end;
begin
end.
-------
Michalis
More information about the fpc-devel
mailing list