Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding parameterless Create with reintroduce?

Tags:

oop

delphi

when i startet with Delphi i read that the only way to avoid useless calls 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?

like image 369
hansmaad Avatar asked Nov 18 '10 09:11

hansmaad


1 Answers

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...

like image 191
Wim ten Brink Avatar answered Nov 15 '22 09:11

Wim ten Brink