开发者

Hiding parameterless Create with reintroduce?

开发者 https://www.devze.com 2023-01-25 12:13 出处:网络
when i startet with Delphi i read that the only way to avoid useless c开发者_StackOverflowalls of the parameterless Create constructor is to throw an exception or assertion in it.

when i startet with Delphi i read that the only way to avoid useless c开发者_StackOverflowalls of the parameterless Create constructor is to throw an exception or assertion in it. When i used the reintroduce keyword the first time this week, i found out that it seems to solve this problem too.

Test = class
private
    n_ : Integer;
public
    constructor Create(n : Integer); reintroduce;
end;

A call to Test.Create gives me the desired compiler error. Are there any problems with this approach?


Well, simple problem: If you reintroduce a method, it will hide the parent method(s). This should be exactly what you want, but check this code:

type
  TClassParent = class
  public
    procedure DoSomething; overload;
    procedure DoSomething(Something: Integer); overload;
  end;
  TClassChild = class(TClassParent)
  public
    procedure DoSomething(SomethingElse: string); reintroduce;
  end;
var
  Child: TClassChild;
begin
  Child := TClassChild.Create;
  Child.DoSomething;
  Child.DoSomething(1024);
  Child.DoSomething('Something');

This gives you two errors! Why? Because both DoSomething methods in the parent are now hidden! Sometimes, you want this. Other times, you don't. And when you don't, you need to add those missing methods to the child class again, calling the inherited method like this:

procedure TClassChild.DoSomething(SomethingElse: string);
begin
  inherited DoSomething(SomethingElse);
end;

Then again, this is what you want, right? Hiding all parent methods with the same name. Just don't forget that you can still call the inherited methods, though.
Also be aware when you link interfaces to the parent class. The child class will still support the interface but calling the methods through the interface instead of object will result in a call to the parent, not the child!
Reintroducing methods is a good practice in case you want to hide methods from the parent. It will also hide virtual methods with the same name, though! Normally, it would be nicer to just override virtual methods but when changing the parameter list, the use of reintroduce would actually disable the parent class in normal circumstances from outside the class. Within the class, you still have access to them, with no warnings...


If you define a constructor with another signature, you effectively hide the other constructor hence the warning. The directive reintroduce tells the compiler you know what you are doing so it does not show the warning.

So the only effect is that you hide the previous constructor.

If you want multiple variants of the constructor, you can use the overload directive.

0

精彩评论

暂无评论...
验证码 换一张
取 消