SITUATION
This question may be very easy but I am new to Delphi and I'm studying it right now. To better understand classes, I've made one that calculates the solutions of second degree equations. 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;
This is pretty easy indeed but I'd like to focus on the constructor
.
QUESTION
From the book I'm reading I know that (even if the (TObject)
is not needed) my class is actually a sub-class of TObject. For this reason I can call the constructor Create
with no parameters by default. 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 the inherited
? I have studied that, using the keyword I've just mentioned, I am going to "copy" the behavior of the Create
constructor in TObject inside my class. I need to create the object for sure, but then I also need to set default values for my parameters.
Since it's not very well explained, I haven't understood when I have to use inherited
. Should I do it in this case?
Inherited is not strictly needed if you know the parent is TObject. (If you look at the constructor of TObject it is empty). However it is bad practice, in my opinion not to call the inherited constructor, for several reasons that I will outline in a moment. But first, how to call the inherited constructor is like this
constructor TEqSecGrado.Create(a, b, c: double);
begin
inherited Create; // Note that we need to explicitly write "Create" here because it doesn't have 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 would we need to call it?
It is all to do with maintenance, and what happens six months down the line when we have forgotten what we did and why.
Firstly it may be that we decide to refactor and inherit from something other than TObject. If we have included the inherited constructor now, either it will still be valid later, or the compiler will tell us we need to do something.
Secondly, we do not control TObject, the Delphi compiler writers do. It may be that in the future TObject.Create is not empty. Imagine having to go through all our constructors to add the inherited one in! Of course, there would be an outcry from all those programmers who thought it was a waste of time, so it will never happen. Probably.
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