Initializing Owned Classes

From RAD Studio
Jump to: navigation, search

Go Up to Publishing the Pen and Brush

If you add classes to your component, the component's constructor must initialize them so that the user can interact with the objects at run time. Similarly, the component's destructor must also destroy the owned objects before destroying the component itself.

Because you have added a pen and a brush to the shape control, you need to initialize them in the shape control's constructor and destroy them in the control's destructor:

  1. Construct the pen and brush in the shape control constructor:
constructor TSampleShape.Create(AOwner: TComponent);
  inherited Create(AOwner);                      { always call the inherited constructor }
  Width := 65;
  Height := 65;
  FPen := TPen.Create;                                               { construct the pen }
  FBrush := TBrush.Create;                                         { construct the brush }
__fastcall TSampleShape::TSampleShape(TComponent* Owner) : TGraphicControl(Owner)
  Width = 65;
  Height = 65;
  FBrush = new TBrush();                               // construct the pen
  FPen = new TPen();                                   // construct the brush
  1. Add the overridden destructor to the declaration of the component class:

      TSampleShape = class(TGraphicControl)
      public                                                  { destructors are always public}
        constructor Create(AOwner: TComponent); override;
        destructor Destroy; override;                          { remember override directive }
    class PACKAGE TSampleShape : public TGraphicControl
    public:                                                // destructors are always public
        virtual __fastcall TSampleShape(TComponent* Owner);
        __fastcall ~TSampleShape();                        // the destructor
  2. Write the new destructor in the implementation part of the unit:

    destructor TSampleShape.Destroy;
      FPen.Free;                                                    { destroy the pen object }
      FBrush.Free;                                                { destroy the brush object }
      inherited Destroy;                         { always call the inherited destructor, too }
    __fastcall TSampleShape::~TSampleShape()
      delete FPen;                                         // delete the pen object
      delete FBrush;                                       // delete the brush object

See Also