From RAD Studio
Jump to: navigation, search

Go Up to Using Interfaces

When defining a class that supports one or more interfaces, it is convenient to use TInterfacedObject as a base class because it implements the methods of IInterface. TInterfacedObject class is declared in the System unit as follows:

  TInterfacedObject = class(TObject, IInterface)
    FRefCount: Integer;
    function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
    function _AddRef: Integer; stdcall;
    function _Release: Integer; stdcall;
    procedure AfterConstruction; override;
procedure BeforeDestruction; override;
class function NewInstance: TObject; override;
    property RefCount: Integer read FRefCount;

Deriving directly from TInterfacedObject is straightforward. In the following example declaration, TDerived is a direct descendant of TInterfacedObject and implements a hypothetical IPaint interface.

  TDerived = class(TInterfacedObject, IPaint)

Because it implements the methods of IInterface, TInterfacedObject automatically handles reference counting and memory management of interfaced objects. For more information, see Memory Management of Interface Objects, which also discusses writing your own classes that implement interfaces but that do not follow the reference-counting mechanism inherent in TInterfacedObject.

See Also