[fpc-pascal] Class vs Object type
Santiago A.
svaa at ciberpiula.net
Thu Apr 7 12:58:14 CEST 2016
El 06/04/2016 a las 13:23, Graeme Geldenhuys escribió:
> "The difference between objects and classes is mainly that an object is
> allocated on the stack, as an ordinary record would be, and that classes
> are always allocated on the heap."
>
> Are there pros or cons to either?
>
> Regards,
> - Graeme -
A nice pro of objects is that, if you don't need a constructor, you can
forget about calling create and free.
If you need a constructor (ie it has virtual methods), there is not that
advantage.
Moreover, if the object uses classes instances that must be freed, you
also must call destructor, then any advantage is over. Maybe a little
performance gain using stack instead of heap.
A nice feature would be default creator and destructor:
ej.
type
TMyObject=Object
constructor default;
Destructor default;
end;
procedure foo;
var
obj:TMyObject;
begin
// Default constructor (if it has) automatically called here
obj.xxxx;
obj.zzz;
// Default destructor automatically called here
end;
Or even with parameters
type
TMyObjectParam=Object
constructor default(n:Integer);
Destructor default;
end;
procedure foo;
var
obj1:TMyObjectParam(7);
obj2:TMyObjectParam;
begin
// Default constructor of obj1 automatically called here with param 7
// Default constructor of obj2 not called because the declaration has no parameters
obj1.xxxx;
obj1.zzz;
if condition then begin
obj2.Default(x); // Constructor must be called manually
obj2.xxxx;
obj2.zzz;
end;
// Default destructor of obj2 automatically called here if it has been initializated
// Default destructor of obj1 automatically called here
end;
--
Saludos
Santi
svaa at ciberpiula.net
More information about the fpc-pascal
mailing list