While it is possible to overload ^
to do exponentiation, you shouldn't. It's a bad idea.
@AaronF's answer shows how ugly the code to do this is, but that's only the tip of the iceberg. The real problem comes when you try to actually use this in real code. The problems stem from one simple fact: overloading an operator changes the actions carried out by that operator, but does not affect either the precedence or associativity of that operator. In the case of ^
, both the precedence and the associativity are completely wrong for exponentiation.
precedence
In C++, the ^
operator has quite low precedence. Exponentiation should have very high precedence. For example, an expression like x^y*z
would normally mean xyz--but what it will mean in C++ is xyz. In fact in C++, ^
has precedence even lower than addition and subtraction, so even x^y+z
comes out wrong--it means xy+z instead of the xy+z that you'd want/normally expect.
Associativity
Exponentiation is right associative--but in C++, the ^
operator is left associative. For example, given an expression like x^y^z
, what you'd want/expect would be for it to mean xyz, but what you'll get is (xy)z (equivalent to xyz).
Result
These mean that if you do overload operator^
to do exponentiation, you'll only have gotten away from using the name pow
. You will not get away from most of the parentheses; in any non-trivial expression, you'll still need parentheses to force the proper precedence and associativity, because as outlined above, the precedence and associativity C++ assigns to operator^
are both entirely wrong for exponentiation.
Conclusion
Although you can overload operator^
to do exponentiation, this is one of those places where discretion is the better part of valor. When you overload operators in C++, you really have three factors to take into account: the name, the precedence and the associativity. For a good operator overload, all three should be right. It's sometimes reasonable to do an overload where only two out of three are right, and the third isn't too far off. In this case, only one out of the three is even close to right; the other two are completely wrong.
Don't do this. It's a bad idea.