Class helpers

Top  Previous  Next

New features since Delphi 7 > Class helpers

 

 

There is no counterpart to class/record helpers in C++.

 

For C++Builder for TCharHelper there are library functions declared in System.Character.hpp, which have to be used instead. For example

 

 

s[1] := s[1].ToUpper;

 

->

 

s[1] = ToUpper(s[1]);

 

 

How code that uses helpers can be translated to C++ in other cases for C++Builder and for other compilers is demonstrated at the example from here:

 

http://delphi.about.com/od/oopindelphi/a/understanding-delphi-class-and-record-helpers.htm

 

 

TStringsHelper = class Helper for TBase

private 

  function GetTheObject(const AString: String): TObject; 

  procedure SetTheObject(const AString: String; const Value: TObject); 

public 

  property ObjectFor[const AString : String]: TObject Read GetTheObject Write SetTheObject; 

end;

 

becomes with Delphi2Cpp for C++Builder  to

 

class TStringsHelper

{

  public:

  TStringsHelper(TBase* xpClass) : m_pClass(xpClass) {}

 

private:

  TObject* __fastcall GetTheObject(const String& AString);

  void __fastcall SetTheObject(String& AString, TObject* Value);

public:

  __property TObject* ObjectFor[const String& AString] = { read = GetTheObject, write = SetTheObject };

 

  private:

 

  TBase* m_pClass;

 

};

 

 

Of course, for other compilers than C++Builder the properties become setter and getter functions. If S is an instance of TBase, an assignment of a TObject like:

 

S.ObjectFor['a'] := Object;

 

becomes to:

 

TStringsHelper(s).ObjectFor[L"a"] = Object;

 

 

The trick is, that functions calls of the helper class are redirected to calls of the helped class inside of a local instance of the helper class. For example the setter method of TStringHelper might look like:

 

 

void __fastcall TStringsHelper::SetTheObject(String& AString, TObject* Value)

{

  int idx = 0;

  idx = m_pClass->IndexOf(AString);

  if(idx >- 1)

    m_pClass->Objects[idx] = Value;

}

 

 

Till the Delphi compiler 10 Seattle it was allowed to access private members of the helped class via its class helper regardless in which unit the helped class was declared. With the just described C++ pendant this is not possible. However, this possibility broke OOP encapsulation rules and was regarded as a bug, which was fixed with Delphi compiler 10.1 Berlin. You can read more about this bug fix here:

 

 

http://blog.marcocantu.com/blog/2016-june-closing-class-helpers-loophole.html

 

 

 



This page belongs to the Delphi2Cpp Documentation

Delphi2Cpp home  Content