inheritance - How To Override a Delphi Object from a Third Party -
i using third party reporting vcl package in delphi 2007. want add code each of functions couple of objects of package have. but, want without having re-write lot of code in application. have following:
tbasereport (base object abstract functions) | -------------- | | tviewreport tprintreport (descendents actual implementation of functions)
the reporting package calls number of events during report print process. each event passed tobject parameter instance of either tviewreport (if viewing report on screen) or tprintreport (if printing directly). example:
function tform1.beforeprint(sender: tobject); begin tbasereport(sender) // type cast tbasereport code works either begin // tviewreport or tprintreport. .... code here ... end; end;
what create new descendent of tbasereport (say tmybasereport) of same functions overrided call of own code first before calling inherited code. problem have, of course, cannot override tbasereport because of it's functions abstract. created 2 objects override tviewreport , tprintreport. tried following:
type tmyreportprinter = class(treportprinter) public procedure printtext(x, y: integer; s: string); override; end; tmyviewreport = class(tviewreport) public procedure printtext(x, y: integer; s: string); override; end; . . . function tform1.beforeprint(sender: tobject); var rpt: tbasereport; begin if sender treportprinter rpt := tmyreportprinter(sender) else rpt := tmyviewreport(sender); rpt begin printtext(1.5, 1.5, 'foobar'); .... same original code here ... end; end; procedure tmyreportprinter.printtext(x, y: integer; s: string); begin inherited; logmsg('printtext called.'); end; procedure tmyviewreport.printtext(x, y: integer; s: string); begin inherited; logmsg('printtext called.'); end;
but code in tmyreportprinter , tmyviewreport never called. there anyway override object if don't have control on creation of object begin with?
i assume printtext not defined virtual method, can't override it.
maybe there event (like onbeforeprinttext) can used add functionality.
else should redefine of functionality.
the difference between static , dynamic linking
when have class 2 methods , subclass overrides 1 of them:
type tbaseclass = class public procedure methoda; // calls methodb procedure methodb; end; tsubclass = class (tbaseclass) public procedure methodb; end;
now have object of tsubclass , call methoda. then methodb of tbaseclass called. called static linking. methodb of tsubclass not called methoda of tbaseclass.
but if declare methodb virtual, , use override in tsubclass:
type tbaseclass = class public procedure methoda; // calls methodb procedure methodb; virtual; end; tsubclass = class (tbaseclass) public procedure methodb; override; end;
now methodb dynamically linked. when call methoda on object of class tsubclass, methodb of tsubclass called.
Comments
Post a Comment