Overriding the Constructor and Destructor
Go Up to Creating a graphic component Index
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.
- Add the overridden constructor to the declaration of the component class:
type TSampleShape = class(TGraphicControl) public { constructors are always public } constructor Create(AOwner: TComponent); override { remember override directive } end;
class PACKAGE TSampleShape : public TGraphicControl { public: virtual __fastcall TSampleShape(TComponent *Owner); };
- 2. Redeclare the Height and Width properties with their new default values:
type TSampleShape =</source> class(TGraphicControl) . . . published property Height default 65; property Width default 65; end;
class PACKAGE TSampleShape : public TGraphicControl { . . . __published: __property Height; __property Width; }
- 3. Write the new constructor in the implementation part of the unit:
constructor TSampleShape.Create(AOwner: TComponent); begin inherited Create(AOwner); { always call the inherited constructor } Width := 65; Height := 65; end;
__fastcall TSampleShape::TSampleShape(TComponent* Owner) : TGraphicControl(Owner) { Width = 65; Height = 65; }