Operator overloading

João Eiras joao.eiras at gmail.com
Mon Dec 17 13:04:59 PST 2007

Hi all,

there's a feature in C++ which I like a lot, and I think it would be  
interesting to have in es4, which is operator overloading, like

   class X{ X& operator+(const X& x); }
   X a, b, c; c = a+b;

which allows the programmer to define a sum operation between two objects  
of type X.
The notation I'm using in this e-mail is just for example.
C++ allows to define all operators except :: (scope resolution), .  
(member) and .* (member through pointer)

To keep things clean, new operators cannot be defined (like in C++),so

   class X{ X& operator myop(const X& x); }
   X a, b, c; c = a myop b;

would be invalid.

Operators should only be defined as members of objects, so one cannot  
right a global operator function which picks up two object (alla C++), like
   function operator+:X(x:X,x:X);

Any global operator function like this one before would be added to the  
window, and would be equivalent to do
because the 2nd argument would be ignored.

The following operators should be definable:
  - arithmetic: +  -  *  /  %  +=  -=  *=  /=  %=  ++  --
  - bitwise: &  |  ^  >>  <<  >>=  <<=  ~
  - boolean: ||  &&  !  ||=  &&=
  - others: typeof  ()  []

All these operators are binary except for |, ~ and typeof , so the left  
hand (A) object would be the context object, and the right hand object (B)  
would be the argument passed to the operator member in A. For unary  
operators, there won't be arguments, and the function would be called upon  
its target.
operator functions would only be called if the operator is explicitly used  
in the source code.

Now consider an example
   class X{
     function operator+:X(x:X);
     function operator typeof(){ return "function";};
   var a:X := new X;
   var b:X := new X;

   var c:X = a + b; //sucess, operator is defined

   a += b; //error, no += operator defined

   var c:X = a + 1; //type-error, rhs must be of type X

   var tp:String = typeof a;//sucess, typeof operator is ALWAYS defined, by  
default it works as specified

alternative notation

   class X{}
   X['operator ~'] = function(){};...

Supporting all these operators in the spec can be somewhat awkward. So I  
wish for at least the typeof, () and [] operators to be defined.
This way one can build custom collections, which have the [] indexing  
Defining the () operator would fit the use case of IE and Opera (added for  
compatibility) which support the () operator as indexing operator in  

What do you think ?

Thank you for your attention.

More information about the Es4-discuss mailing list