[Lazarus] Check if an abstract method is implemented or not
Michael Van Canneyt
michael at freepascal.org
Thu Jan 24 14:14:08 CET 2013
On Thu, 24 Jan 2013, Xiangrong Fang wrote:
> This is a clean solution. And as a matter of fact, the compiler does NOT warn me while instantiate class with abstract method.
It definitely does, unless you use a class pointer to do it of course.
In the below example:
TParentClass = Class of TParent;
PC : TParentClass;
You will not get a warning. But if you run the example as I described it, you get:
home: >fpc -S2 -vwh te.pp
te.pp(15,19) Warning: Constructing a class "TChild" with abstract method "MyMethod"
te.pp(5,15) Hint: Found abstract method: procedure MyMethod(<TParent>);
> This is different than Java,
> in which you must implement all abstract method while inherits from an abstract class.
> Why I shall not instantiate a sub-class that has not fully implemented abstract methods of its parent class?
Because then you run the risk that you try to execute a method that is not implemented.
> 2013/1/24 Michael Van Canneyt <michael at freepascal.org>
> On Thu, 24 Jan 2013, xrfang wrote:
> Hi All,
> I wrote a TPainter abstract class, and a TPaintRect class. In the TPaintRect class I have this code:
> procedure TPaintRect.OnMouseEnter(Sender: TObject);
> i: Integer;
> p: TPainter;
> for i := 0 to painters.Count - 1 do begin
> p := TPainter(painters.Objects[i]);
> except on EAbstractError do ; end;
> if Assigned(FOnMouseEnter) then FOnMouseEnter(Sender);
> While running in IDE, the program will crash because OnMouseEnter is abstract.
> My problems are:
> 1) As I already wrapped it with try-except, I hope it won't trigger IDE exception. But even I turn off "Notify on Lazarus Exception" in
> debugger options it
> still pops up, and the popup said RunError(211), NOT EAbstractError. The program runs well outside of IDE.
> 2) Is there a way to detect if an abstract method is implemented or not, without trying to call it and try...except?
> The following will do it:
> uses sysutils;
> TParent = Class
> Procedure MyMethod; virtual; abstract;
> TChild = class(TParent)
> C : TParent;
> If TMethod(@C.MyMethod).Code=Pointer(@system.AbstractError) then
> Writeln('Not implemented')
> When run, it will print 'Not implemented'.
> But you should not instantiate objects with abstract methods to begin with.
> The compiler warns you if you do.
> (compile the above program with warnings/hints to see it)
> Lazarus mailing list
> Lazarus at lists.lazarus.freepascal.org
More information about the Lazarus