Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-pascal / 2020-12

Operators for a class

2 messages · 2 people ·

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Gabor Boros

Hi All,

I try to convert some C++ source to FPC, see below a short example from it. How can I define same operator with FPC trunk?

class Cla
{

     INT64   Num;

public:
Cla operator +(const Cla& m)
{

         Cla  ret(this);
         ret.Num += m.Num;
         return ret;
     }

Gabor

Reply by email

Sven Barth
to Gabor Boros
Gabor Boros wrote 18 lines
Hi All, I try to convert some C++ source to FPC, see below a short example from it. How can I define same operator with FPC trunk? class Cla {     INT64   Num; public:     Cla operator +(const Cla& m)     {         Cla  ret(this);         ret.Num += m.Num;         return ret;     }

Depending on the usecase of that class it might be better to declare it as a record, then you can declare the operator as an operator in Pascal as well (in C++ class and struct are rather interchangeable with the main difference being the default visibility (private for class and public for struct)):

=== code begin ===

// interface section
type
   Cla = record
     Num: Int64;
     class operator + (const aLeft, aRight: Cla): Cla;
   end;
// implementation section
class operator Cla.+(const aLeft, aRight: Cla): Cla;
begin
   Result := Default(Cla);
   Result.Num := aLeft.Num + aRight.Num;
end;

=== code end ===

Otherwise you need to declare a global operator overload (which will not work with generics):

=== code begin ===

// in interface section
operator + (aLeft, aRight: TCla): TCla;
// in implementation section
operator +(aLeft, aRight: TCla): TCla;
begin
   Result := TCla.Create;
   Result.Num := aLeft.Num + aRight.Num;
end;

=== code end ===

Please note that in both cases the operators in Pascal are static functions, not member methods.

Regards,
Sven

Reply by email