class methods

Top  Previous  Next

What is translated > class methods

 

A Delphi class method can be called through a class reference or an object reference, like C++ static methods.

 

type

 TBase = class(TObject)

 public

    class function ClassMethod(xi: Integer): Integer;

 end;

 

...

 

var

  pBase: TBase;

  i : Integer;

begin

  i := TBase.ClassMethod(0);  // calling through a class reference

  pBase := TBase.Create;

  i := pBase.ClassMethod(0);  // calling through a object reference

 

 

The first intuition would be a translation in the following way:

 

class TBase: public TObject {

  static int __fastcall ClassMethod( int xi );

};

 

...

 

TBase* pBase = NULL;

int i = 0;

TBase::ClassMethod( 0 );  // calling through a class reference

pBase = new TBase;

pBase->ClassMethod( 0 );  // calling through a object reference

 

 

But there are two reasons why this translation doesn't suffice.

 

1.In the defining declaration of a class method, the identifier Self represents the class where the method is called. In C++ however inside of a static function there is no counterpart to Delphi's Self (this isn't defined her).
2.Delphi class methods can be virtual, C++ static methods cannot.Therefore Delphi2Cpp has to use a tricky construction to reproduce this ability of Delphi.:

 

Both problems can be solved, if an additional pointer to an instance of the class is passed to the function.

 

non virtual class methods

virtual class methods

 

 

So the translation looks like:

 

class TBase: public TObject {

  static int __fastcall ClassMethod( const TBase* xpTHIS, int xi );

};

 

...

 

TBase* pBase = NULL;

int i = 0;

TBase::ClassMethod( TBase::__tp.SObjectType(), 0 );

pBase = new TBase;

pBase->ClassMethod( pBase, 0 );

 

 

 



This page belongs to the Delphi2Cpp Documentation

Delphi2Cpp home  Content