RAD Studio |  |

Initializing Owned Classes

If you add classes to your component, the component's constructor must initialize them so that the user can interact with the objects at runtime. 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:

Copy Code

    constructor TSampleShape.Create(AOwner: TComponent);
    begin
      inherited Create(AOwner);                      { always call the inherited constructor }
      Width := 65;
      Height := 65;
      FPen := TPen.Create;                                               { construct the pen }
      FBrush := TBrush.Create;                                         { construct the brush }
    end;

Copy Code

    __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:

Copy Code

    type
      TSampleShape = class(TGraphicControl)
      public                                                  { destructors are always public}
        constructor Create(AOwner: TComponent); override;
        destructor Destroy; override;                          { remember override directive }
      end;

Copy Code

    class PACKAGE TSampleShape : public TGraphicControl
    {
      .
      .
      .
    public:                                                // destructors are always public
        virtual __fastcall TSampleShape(TComponent* Owner);
        __fastcall ~TSampleShape();                        // the destructor
        .
        .
        .
    };

1. Write the new destructor in the implementation part of the unit:

Copy Code

    destructor TSampleShape.Destroy;
    begin
      FPen.Free;                                                    { destroy the pen object }
      FBrush.Free;                                                { destroy the brush object }
      inherited Destroy;                         { always call the inherited destructor, too }
    end;

Copy Code

    __fastcall TSampleShape::~TSampleShape()
    {
      delete FPen;                                         // delete the pen object
      delete FBrush;                                       // delete the brush object
    }

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!