[fpc-pascal] How to know if a class implements a method
Matt Emson
memsom at interalpha.co.uk
Fri May 18 15:44:28 CEST 2007
> Any idea how I know if a class, in a class pointer, overrides a virtual
> method? Eg:
<snip>
> vfooclass := tboo1;
> // vfooclass doesn't implement sample.
>
> vfooclass := tboo2;
> // vfooclass implements sample.
You need to implement a virtual method, even if it does nothing. Are you
sure you're not meaning abstract method?
e.g.
TBlah = class
public
procedure blah; virtual;
procedure blahblah; virtual; abstract;
end;
Will only compile if "TBlah.blah" has a body.... where as TBlah.blahblah"
does not require itself to be implemnted.
> At this moment I know that:
>
> 1. I could cast a method pointer with tmethod if sample was a class
method;
>
> 2. I could cast this same method pointer if I had an instance of
vfooclass.
>
> But is there another way beyond creating an instance?
You can always hack the RTTI/VMT, but that might not be a safe way.
Might it be that you need to have a more complex inheritence tree? So add a
few levels?
tfooBaseclass = class of tfooBase;
tfooclass = class of tfoo;
tfooBase = class
private
procedure sample; virtual;
end;
tfoo = class(tfooBase)
public
procedure sample; override; //a base implementation
end;
tboo1 = class(tfooBase)
//sample is still private and not publicly accessable
end;
tboo2 = class(tfoo)
public
procedure sample; override; //whatever
end;
if (x is tfoo ) then {supports the sample};
if (x is tfooBase ) then {does not make public the sample};
You then know that tfooBaseclass never implement sample, but that all
tfooClass have that method. It all seems a little confusing though. I'm not
really clear what you are trying to achieve. Inheritence wants you to either
make methods static, or virtual. If it is static, you can't override it,
only "hide" (Replace) it.
You coule also use interfaces. Then you don't need a base class:
ifoo = interface
private
procedure sample; virtual;
end;
tboo1 = class( ifoo)
procedure sample;
end;
tboo2 = class
end;
if (tboo is ifoo) then {supports the ifoo interface};
More information about the fpc-pascal
mailing list