Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Class References

Tags:

c++

delphi

rtti

Coming from Delphi, I'm used to using class references (metaclasses) like this:

type
  TClass = class of TForm;
var
  x: TClass;
  f: TForm;
begin
  x := TForm;
  f := x.Create();
  f.ShowModal();
  f.Free;
end;

Actually, every class X derived from TObject have a method called ClassType that returns a TClass that can be used to create instances of X.

Is there anything like that in C++?

like image 845
Bruno Santos Avatar asked Jan 10 '23 18:01

Bruno Santos


1 Answers

Metaclasses do not exist in C++. Part of why is because metaclasses require virtual constructors and most-derived-to-base creation order, which are two things C++ does not have, but Delphi does.

However, in C++Builder specifically, there is limited support for Delphi metaclasses. The C++ compiler has a __classid() and __typeinfo() extension for retrieving a Delphi-compatible TMetaClass* pointer for any class derived from TObject. That pointer can be passed as-is to Delphi code (you can use Delphi .pas files in a C++Builder project).

The TApplication::CreateForm() method is implemented in Delphi and has a TMetaClass* parameter in C++ (despite its name, it can actually instantiate any class that derives from TComponent, if you do not mind the TApplication object being assigned as the Owner), for example:

TForm *f;
Application->CreateForm(__classid(TForm), &f);
f->ShowModal();
delete f;

Or you can write your own custom Delphi code if you need more control over the constructor call:

unit CreateAFormUnit;

interface

uses
  Classes, Forms;

function CreateAForm(AClass: TFormClass; AOwner: TComponent): TForm;

implementation 

function CreateAForm(AClass: TFormClass; AOwner: TComponent): TForm;
begin
  Result := AClass.Create(AOwner);
end;

end.

#include "CreateAFormUnit.hpp"

TForm *f = CreateAForm(__classid(TForm), SomeOwner);
f->ShowModal();
delete f;
like image 83
Remy Lebeau Avatar answered Jan 14 '23 20:01

Remy Lebeau