RAD Studio |  |

Overriding the Constructor and Destructor
Changing default property values
Collapse All

To change default property values and initialize owned classes for your component, you must override the inherited constructor and destructor. In both cases, remember always to call the inherited method in your new constructor or destructor.

Changing default property values

The default size of a graphic control is fairly small, so you can change the width and height in the constructor. Changing default property values is explained in more detail in Modifying an existing component.

In this example, the shape control sets its size to a square 65 pixels on each side.

1. Add the overridden constructor to the declaration of the component class:

Copy Code

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

Copy Code

    class PACKAGE TSampleShape : public TGraphicControl
    {
    public:
        virtual __fastcall TSampleShape(TComponent *Owner);
    };

1. Redeclare the Height and Width properties with their new default values:

Copy Code

    type
      TSampleShape = class(TGraphicControl)
      .
      .
      .
      published
        property Height default 65;
        property Width default 65;
      end;

Copy Code

    class PACKAGE TSampleShape : public TGraphicControl
    {
      .
      .
      .
    __published:
        __property Height;
        __property Width;
    }

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

Copy Code

    constructor TSampleShape.Create(AOwner: TComponent);
    begin
      inherited Create(AOwner);  { always call the inherited constructor }
      Width := 65;
      Height := 65;
    end;

Copy Code

    __fastcall TSampleShape::TSampleShape(TComponent* Owner) : TGraphicControl(Owner)
    {
      Width = 65;
      Height = 65;
    }

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