Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi 7: create a new instance of an unknown object

I have a TObject reference to a instance of an unkown class. How do I call the constructor of this unknown class to create another instance of it? I know that Delphi has RTTI, but it isn't clear how to use it.

like image 530
neves Avatar asked Nov 06 '14 17:11

neves


1 Answers

You can't construct an object of unknown type. The compiler has to know the correct class type at compile-time so it can generate the proper code. What if the constructor requires parameters? How many? What data types? Are they passed by stack or registers? This information is important.

That being said, if the classes in question are all derived from a common base class that has a virtual constructor, THEN and ONLY THEN can you construct such objects. You can use the TObject.ClassType() method to get a reference to the class type of the existing object, type-cast it to the base class type, and call the constructor. For example:

type
  TBase = class
  public
    constructor Create(params); virtual;
  end;

  TBaseClass = class of TBase;

  TDerived1 = class(TBase)
  public
    constructor Create(params); override;
  end;

  TDerived2 = class(TBase)
  public
    constructor Create(params); override;
  end;

  ...

var
  NewObj: TBase;
begin
  if SomeObj is TBase then
    NewObj := TBaseClass(SomeObj.ClassType).Create(params);
end;
like image 167
Remy Lebeau Avatar answered Nov 15 '22 03:11

Remy Lebeau