TInterfacedObject

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:

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

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

type
  TDerived = class(TInterfacedObject, IPaint)
  .
  .
  .
  end;

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