Hide without options Create with re-entry?

When I start with Delphi, I read that the only way to avoid useless calls to the constructor constructor without parameters is to throw an exception or statement into it. When I used the reintroduce keyword for 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; 

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

+6
oop delphi
source share
2 answers

Well, a simple problem: if you re-enter the 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 mistakes ! What for? Because both DoSomething methods in the parent are now hidden! Sometimes you want it. In other cases, you do not. And when you do not, you need to add these missing methods again to the child class by calling the inherited method as follows:

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

Again, this is what you want, isn't it? Hide all parent methods with the same name. Just remember that you can still call inherited methods.
Also keep in mind when you bind interfaces to the parent class. The child class will still support the interface, but calling methods through the interface instead of the object will cause the parent, not the child, to be called!
Re-introducing methods is good practice if you want to hide methods from the parent. However, it will hide virtual methods with the same name! Generally, it would be better to simply override the virtual methods, but if you change the parameter list, using re-entry will actually disable the parent class under normal circumstances outside the class. Inside the class, you have access to them, without warning ...

+4
source share

If you define a constructor with a different signature, you are actually hiding another constructor, hence the warning. The reintroduce directive tells the compiler that you know what you are doing so that it does not display a warning.

So the only effect is that you are hiding the previous constructor.

If you want several constructor options, you can use the overload directive.

+1
source share

All Articles