Operator Overloading  «Prev  Next»
Lesson 6 The operator keyword
Objective Use the Operator Keyword to overload Operators

Use the Operator Keyword in C++ to overload existing operators

To overload operators, you use the operator keyword similarly to how you used it to overload functions.
For example:
class foo {
foo  operator-();      //overload unary minus
foo  operator-(int);   //binary minus foo-int
foo  operator-(foo);   //binary minus foo-foo

foo operator-(int, foo);   //binary minus int-foo
foo operator-(int, foo*);  //illegal:need foo or foo&

Notice that it is our style to omit spaces between the keyword operator, the operator to be overloaded, and the signature.
Overloadable operators
+    -    *    /    =    <    >    +=   -=   *=   /=   <<   >>
<<=  >>=  ==   !=   <=   >=   ++   --   %    &    ^    !    |
~    &=   ^=   |=   &&   ||   %=   []   ()   ,    ->*  ->   new 
delete    new[]     delete[]

Operator conversion

The second way to produce automatic type conversion is through operator overloading. You can create a member function that takes the current type and converts it to the desired type using the operator keyword followed by the type you want to convert to. This form of operator overloading is unique because you do not appear to specify a return type.
The return type is the name of the operator you are overloading. Here is an example:
//: C12:OperatorOverloadingConversion.cpp
class Three {
 int i;
  Three(int ii = 0, int = 0) : i(ii) {}
class Four {
 int x;
  Four(int xx) : x(xx) {}
  operator Three() const { return Three(x); }
void g(Three) {}
 int main() {
 Four four(1);
 g(1); // Calls Three(1,0)
} ///:~

With the constructor technique, the destination class is performing the conversion, but with operators, the source class performs the conversion. The value of the constructor technique is that you can add a new conversion path to an existing system as you are creating a new class. However, creating a single-argument constructor always defines an automatic type conversion (even if it has more than one argument, if the rest of the arguments are defaulted), which may not be what you want (in which case you can turn it off using explicit). In addition, there is no way to use a constructor conversion from a user-defined type to a built-in type; this is possible only with operator overloading.