Delphi inherits Create from TObject

SITUATION

This question may be very easy, but I'm new to Delphi, and am studying it now. To better understand the classes, I did what calculates the solutions of equations of the second degree. This is the code:

type TArrayOfStrings = array of string; type TEqSecGrado = class(TObject) sealed private a, b, c: double; delta: double; solutions: TArrayOfStrings; function getDelta(vala, valb, valc: double): double; overload; public constructor Create(a, b, c: double); function getDelta: double; overload; function getSolutions: TArrayOfStrings; virtual; end; 

It's pretty simple, but I would like to focus on the constructor .


Question

From the book I'm reading, I know that (even if (TObject) not needed) my class is actually a subclass of TObject. For this reason, I can call the Create constructor with no default parameters. My question is:

 constructor TEqSecGrado.Create(a, b, c: double); begin //inherited; -> is it needed? Self.a := a; Self.b := b; Self.c := c; delta := 0; end; 

Do I need to call inherited ? I studied this using the keyword just mentioned, I'm going to "copy" the behavior of the Create constructor into a TObject inside my class. I need to create an object exactly, but then I also need to set default values ​​for my parameters.

Since this is not well explained, I did not understand when I need to use inherited . Should I do this in this case?

+5
source share
1 answer

Inherited is not strictly necessary if you know that the parent is a TObject. (If you look at the TObject constructor, it is empty). However, it is a bad practice, in my opinion, not to name an inherited constructor for several reasons, which I plan in a moment. But, firstly, how to call an inherited constructor like this:

 constructor TEqSecGrado.Create(a, b, c: double); begin inherited Create; // Note that we need to explicitly name create here because it does not hae the same parameters as our create Self.a := a; Self.b := b; Self.c := c; delta := 0; end; 

But if the inherited constructor is empty, why should we call it?

This is all that is related to maintenance, and what happens six months after we forgot what we did and why.

First, perhaps we decided to reorganize and inherit something other than TObject. If we included the inherited constructor, either it will still be valid later, or the compiler will tell us that we need to do something.

Secondly, we do not control TObject, the creators of the Delphi compiler. Perhaps in the future TObject.Create is not empty. Imagine that you need to go through all of our constructors to add an inherited one! Of course, there would be a protest from all those programmers who thought it was a waste of time, so this would never happen. Maybe.

+16
source

All Articles