C++ : Operator overloading



PART 5

Q21: What is operator overloading?
A: Operator overloading allows the basic C/C++ operators to have user-defined
meanings on user-defined types (classes).  They are syntactic sugar for
equivalent function calls; ex:

	class X {
	  //...
	public:
	  //...
	};

	X add(X, X);	//a top-level function that adds two X's
	X mul(X, X);	//a top-level function that multiplies two X's

	X f(X a, X b, X c)
	{
	  return add(add(mul(a,b), mul(b,c)), mul(c,a));
	}

Now merely replace `add' with `operator+' and `mul' with `operator*':

	X operator+(X, X);	//a top-level function that adds two X's
	X operator*(X, X);	//a top-level function that multiplies two X's

	X f(X a, X b, X c)
	{
	  return a*b + b*c + c*a;
	}



Q22: What operators can/cannot be overloaded?
A: Most can be overloaded. The only C operators that can't be are `.' and `?:'
(and `sizeof', which is technically an operator).  C++ adds a few of its own
operators, most of which can be overloaded except `::' and `.*'.

Here's an example of the subscript operator (it returns a reference).
First withOUT operator overloading:
	class Vec {
	  int data[100];
	public:
	  int& elem(unsigned i) { if (i>99) error(); return data[i]; }
	};

	main()
	{
	  Vec v;
	  v.elem(10) = 42;
	  v.elem(12) += v.elem(13);
	}

Now simply replace `elem' with `operator[]':
	class Vec {
	  int data[100];
	public:
	  int& operator[](unsigned i) { if (i>99) error(); return data[i]; }
	};   //^^^^^^^^^^--formerly `elem'

	main()
	{
	  Vec v;
	  v[10] = 42;
	  v[12] += v[13];
	}



Q23: Can I create a `**' operator for `to-the-power-of' operations?
A: No.

The names of, precedence of, associativity of, and arity of operators is fixed
by the language.  There is no `**' operator in C++, so you cannot create one
for a class type.

If you doubt the wisdom of this approach, consider the following code:
	x = y ** z;
Looks like your power operator?  Nope.  z may be a ptr, so this is actually:
	x = y * (*z);
Lexical analysis groups characters into tokens at the lowest level of the
compiler's operations, so adding new operators would present an implementation
nightmare (not to mention the increased maintenance cost to read the code!).

Besides, operator overloading is just syntactic sugar for function calls.  It
does not add fundamental power to the language (although this particular
syntactic sugar can be very sweet, it is not fundamentally necessary).  I
suggest you overload `pow(base,exponent)', for which a double precision version
is provided by the ANSI-C  library.

By the way: operator^ looks like a good candidate for to-the-power-of, but it
has neither the proper precedence nor associativity.