On 24/11/2011 05:47, Graeme Geldenhuys wrote:
On 2011-11-24 03:58, Luiz Americo Pereira Camara wrote:
possible to get the expected behavior without forcing programmer to
create a virtual constructor by using the new RTTI
What has the "new RTTI" got to do with anything?

Simply define TObj.Create as virtual, and TFoo.Create as overridden.
This is rather normal coding practise with classes. Nothing special.

This solution is not quite generic because is necessary to descend from an specific class and also needs to change an interface declaration. So to use in old code / classes it would be necessary to change the hierarchy and the interface.

Also it would not work with classes that i cant change the hierarchy like rtl ones or third party

With Delphi is possible to call a constructor even if has a different name from Create and with parameters without changing interface or hierarchy

It seems useful for me

Luiz


----8<-------------8<-------------8<-------------8<-------------8<----
program test;
{$mode ObjFpc}{$H+}
type
   TObj = class
   public
     constructor create; virtual;
   end;
   TObjClass=class of TObj;

   TFoo = class(TObj)
   public
     constructor create; override;
   end;

constructor TObj.Create;
begin
   inherited create;
   WriteLn('TObj.create');
end;

constructor TFoo.create;
begin
   inherited Create;
   WriteLn('TFoo.Create');
end;

var
   cls: TObjClass;
   obj: TObj;
begin
   cls := TFoo;
   WriteLn('cls class is ',cls.ClassName);
   Obj := cls.Create;
   Obj.Free;
end.
----8<-------------8<-------------8<-------------8<-------------8<----


And here is the output...

$ ./test
cls class is TFoo
TObj.create
TFoo.Create



Regards,
   - Graeme -


_______________________________________________
fpc-pascal maillist  -  fpc-pascal@lists.freepascal.org
http://lists.freepascal.org/mailman/listinfo/fpc-pascal

Reply via email to