C++Builder __classid

Top  Previous  Next

What is translated > class-reference type > C++Builder __classid

C++Builder has as counterpart to Delphi's TClass:

 

typedef TMetaClass* TClass

 

A Delphi class reference type is defined as TClass in C++Builder:

 

type TBaseClass = class of TBase;

 

->

 

typedef System::TMetaClass TBaseClass;

 

 

Variables of this type can be defined and classes can be assigned to them. For C++Builder the __classid function is a special extension, to get class references.

 

var

 p : TBase; 

 bc :TBaseClass;

begin

 bc := p;  

 

->

 

TBase* p = nullptr;

TBaseClass bc = nullptr;

bc = __classid(p);

 

 

With such class references code such as:

 

  ClassRef := Sender.ClassType;

 

  while ClassRef <> NIL do

  begin

    s := ClassRef.ClassName);

    ClassRef := ClassRef.ClassParent;

  end;

 

can be translated pretty well as:

 

TClass ClassRef = Sender->ClassType();

  

while(ClassRef != nullptr)

{

  s = ClassRef->ClassName();

  ClassRef = ClassRef->ClassParent();

}

 

 

It is not possible however, to create an instance of a class from such a TClass. To do that, a small Delphi unit has to be added to the C++Builder project. The unit CreateClass.pas, which is delivered with Delphi2Cpp contains the simple function:

 

function CreateObject(C: TClass) : TObject;

begin

  Result := C.Create();

end;

 

When this unit is added to a C++Builder project, automatically a C++ header file "CreateClass.hpp" is created with the declaration:

 

extern DELPHI_PACKAGE System::TObject* __fastcall CreateObject(System::TClass C);  

 

That function can be used now in the C++ code to create class instances from class references:

 

function make(Base: TBaseClass): TBase;

begin                                  

  result := Base.Create;               

end;   

 

->

 

TBase* make(TBaseClass* Base)         

{                                       

  TBase* result = nullptr;             

  result = (TFBase*) CreateObject(Base);            

  return result;                        

}                                       

                              

If the class referenc of a class which is derived from TBase is passed to the make-function an instance of that class will be created.

 

p := make(TDerived); :

 

->

 

P = make(__classid(TDerived));

 

 

 

.



This page belongs to the Delphi2Cpp Documentation

Delphi2Cpp home  Content