At runtime I obtain an instance of descendant of TObject (for example its name is TGoodForm).
The definition of TGoodForm is unknown at compile time (I know that it is TGoodForm from TObject::ClassName()).
The question: how to create new instance of TGoodForm ?
In another words, can I get address of constructor through reference to existing object at runtime?
(Assembler is permitted)

At runtime I obtain an instance of descendant of TObject (for example its name is TGoodForm).
The definition of TGoodForm is unknown at compile time (I know that it is TGoodForm from TObject::ClassName()).
The question: how to create new instance of TGoodForm ?
In another words, can I get address of constructor through reference to existing object at runtime?
(Assembler is permitted)

Can you post code by chance?

for(int i=0, n=form->ComponentCount; i<n; ++i){
    TComponent* comp=form->Components[i];
    if(comp->ClassInfo()=="TGoodForm"){
        // here I want to create new instance of the same class
    }
}

<< moderator edit: added [code][/code] tags >>

Having address of constructor, I'll write:

typedef TObject* __fastcall (*Ctor)(TComponent* owner);
TObject* newObject=(*(Ctor)address)(form);

<< moderator edit: added [code][/code] tags >>

Maybe I'm not understanding you correctly..

Generated: Thu May 12 16:17:59 2005

[[b][u]001[/u][/b]]     for (int i = 0, n = form->ComponentCount; i < n; ++i) {
[[b][u]002[/u][/b]]             TComponent *comp = form->Components[i];
[[b][u]003[/u][/b]]             if (comp->ClassInfo() == "TGoodForm") {
[[b][u]004[/u][/b]]                     [b]TGoodForm *tf = new TGoodForm();        // ????[/b]
[[b][u]005[/u][/b]]             }
[[b][u]006[/u][/b]]     }

But I have no declaration of class TGoodForm (I get instance from runtime library), and compiler doesn't know about TGoodForm::TGoodForm.
But I found the solution:

The solution is to create delphi function which calls virtual constructor

// delphi unit ComponentCreator.pas

unit ComponentCreator;
interface
uses Classes;
function ComponentCreate(cls: TComponentClass; Owner: TComponent): TComponent;
implementation
function ComponentCreate(cls: TComponentClass; Owner: TComponent): TComponent;
begin
ComponentCreate:=cls.Create(Owner);
end;
end.

// C++ unit

#include "ComponentCreator.hpp"

TClass newClass=existingComponent->ClassType();
RegisterClass(newClass);
TComponent* newComponent=ComponentCreate(newClass, form);
UnRegisterClass(newClass);
newComponent->Name=newName;

// It was useful to analyze VCL source file "Classes.pas"

This article has been dead for over six months. Start a new discussion instead.