overloading conversion operators

Top  Previous  Next

New features since Delphi 7 > Operator Overloading > conversion operators

 

 

The translation of the Delphi conversion operators depends on the direction of the conversion. The case, that a class instance is converted to another type is similar to the unary operators.

 

 

class operator TMyClass.Implicit(a: TMyClass): Integer;

var

  myint : integer;

begin

  myint:= a.payload;

  Result:= myint;

end;

 

 

In C++ there is no parameter. A modified copy of the class instance itself is returned instead. All occurrences of the parameter are substituted by this in C++. So the code above becomes to:

 

 

TMyClass::operator int () const

{

  int result = 0;

  int myint = 0;

  myint = this->payload;

  result = myint;

  return result;

}

 

 

If the other way round another type is converted to the class, the operator has to be converted to a class constructor in C++. For example:

 

 

class operator TMyClass.Implicit(a: Integer): TMyClass;

var

  returnrec : TMyClass;

begin

  returnrec.payload:= a;

  Result:= returnrec;

end;

 

 

Becomes to:

 

 

TMyClass::TMyClass(int A)

{

  //#   TMyClass returnrec = {0};

  this->payload = A;

  *this = *this;

}

 

 

Therefore there isn't a return value in C++ and all occurrences of result in the Delphi code have to be substituted by this in C++.

 

For explicit operators simply the keyword explicit has to be added to the C++ declarations.

 

explicit operator int () const

explicit TMyClass(int A)

 

 

 

 

 

 

 



This page belongs to the Delphi2Cpp Documentation

Delphi2Cpp home  Content