[fpc-pascal] Constructors & Destructors 101
Doug Chamberlin
dougchamberlin at earthlink.net
Fri Apr 3 17:25:44 CEST 2009
Bart wrote:
> On 4/3/09, Jonas Maebe <jonas.maebe at elis.ugent.be> wrote:
>> I think what is meant, is that if you create a direct subclass of TObject,
>> there is no need to call TObject's create constructor (e.g., via "inherited
>> create;") from your own constructors. It doesn't hurt if you do it of
>> course, and may be good practice to account for future situations where the
>> parent class may change.
>
> I often wondered abou that.
>
> So if i understand correctly:
>
> Say I have
>
> Type
> TFoo = class;
> private
> fSomeField: Integer;
> public
> constructor Create;
> end;
>
> then
>
> constructor TFoo.Create
> begin
> Inherited Create;
> fSomeField := -1;
> end;
>
> would in essence be equal to
>
> constructor TFoo.Create
> begin
> fSomeField := -1;
> end;
>
> Since TOblect.Create "does nothing".
Essentially, yes.
However, you may create subtle, lurking bugs if you omit that call and
later refactor your code. For example, if you later change
type
TFoo = class
to
type
TFoo = class(TSomeClass)
and TSomeClass has some important work done in it's Create constructor.
If you properly called "inherited Create;" now that important stuff will
get done, just the way you want it to!
<emphasis>
So, the big lesson here is to stick to the proper structure even though
you may have outside knowledge that the form you should follow is not
strictly necessary in all cases.
</emphasis>
More information about the fpc-pascal
mailing list