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?
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.
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.
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:
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).
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With