Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to add "inherited" line into record constructors?

Modern Delphi allows constructors for records. I have the following code:

{ TKMRect }
constructor TKMRect.Create(aPoint: TKMPoint);
begin
  inherited; // <<- Do I need to add this line ?

  Left := aPoint.X;
  Top := aPoint.Y;
  Right := aPoint.X;
  Bottom := aPoint.Y;
end;

My question is - do I need to add inherited line in my records constructors? And why?

like image 954
Kromster Avatar asked Apr 14 '15 12:04

Kromster


People also ask

Can a constructor be inherited from a child class?

Constructors are special and have same name as class name. So if constructors were inherited in child class then child class would contain a parent class constructor which is against the constraint that constructor should have same name as class name.

How to inherit a constructor in C++03?

In C++03 standard constructors cannot be inherited and you need to inherit them manually one by one by calling base implementation on your own. If your compiler supports C++11 standard, there is a constructor inheritance. For more see Wikipedia C++11 article.

Why constructor should have same name as class name?

Constructors are special and have same name as class name. So if constructors were inherited in child class then child class would contain a parent class constructor which is against the constraint that constructor should have same name as class name. For example see the below code:

Can a derived class override the base class constructor in Java?

The most obvious problem with allowing the derived class to override the base class constructor is that the developer of the derived class is now responsible for knowing how to construct its base class(es).


1 Answers

No you don't need to do this because records don't support inheritance and so inherited is a no-op in this context.

FWIW I regard record constructors as an anti pattern. It makes it hard for the reader at the call site to distinguish between value type and reference type. I personally use static class functions named New that return a new value for this purpose. You can argue over whether a different name is better, but it doesn't matter so long is it isn't Create.

like image 164
David Heffernan Avatar answered Sep 23 '22 07:09

David Heffernan