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;
in a constructor with parameters tries to call the same constructor with the same parameters of the superclass. That doesn't exist, so you get an error. Tryinherited Create;
instead. NowTObject.Create
doesn't do anything, but if, one day, you decide to inherit from another class, it will still be valid. – Rudy Velthuisinherit
always inherits constructor or other method from parent class. If such constructor or method is not found in parent class Delphi tries to search it in its parent class etc. If such constructor or method can't be found in any of the parent classes an error is raised. Now – SilverWarior