Stefan has explained why your override isn't working. Basically, whenever you override a virtual method the signatures of the two methods must match exactly. However, I'm strongly opposed to the use of reintroduce
. And I'll explain why at the bottom of this answer. (Please also note that reintroduce quite specifically does not override the ancestor method. It only hides the warning that the method is hiding the ancestor's method.)
A couple of better options:
Use a different name for your constructor
You don't have to name your constructors Create
. You could for example add a second constructor as: constructor CreateWithCaption(AName: string);
. Note that I didn't even make this constructor virtual. Only make methods virtual if you intend them to behave polymorphically. (Which means you want subclasses to be able to change the implementation even when called from the base class.)
This option is very much like overload as suggested by Stefan.
Use a factory method to create your frame
As systems get larger it can be useful to separate the processing of creating some objects from the work they actually do. This is done using factory methods whose sole purpose is to create other objects that are ready to interact with the rest of your system. E.g.
//I've chosen to demonsrate this on a form, but you could also implement a dedicated factory class
function TMyForm.CreateMessageFrame(ACaption: string): TFrame;
begin
//Note the factory method intends the form to own all frames created.
Result := TfrmMesaj.Create(Self);
//The factory method ensures the frame is "ready"
//This does violate Law of Demeter, but you could easily add a method to the fram to resolve that.
Result.Panel1.Color := clRed;
Result.Panel1.Caption := ACaption;
end;
What's wrong with reintroduce
anway?
- Reintroduce is only applicable when the method on the base class is virtual.
- The method should only be virtual if it's intended to be used polymorphically.
- This means that the method is intended to be called from a base class reference, but might need to take special action to work correctly in some subclasses.
Since your question was dealing with overriding TComponent.Create
, it will serve very nicely to illustrate by way of example.
constructor TComponent.Create(AOwner: TComponent);
is virtual quite specifically so component creation behaves polymorphically. This is so that when components are streamed from a .DFM file they will be created correctly even though the reference used to create them is of type TComponent
.
- If you hide this constructor, then any special actions you need to take when your frame is streamed and created from a .DFM will not happen.
- Also any subclasses of your frame will not be able to override
constructor Create(AOwner: TComponent);
because it is hidden.