3
votes

I wrote an application in which I often use pow function from math.h library. I tried to overload operator^ to make exponentiation easier and faster. I wrote this code:

#include <iostream>
#include <math.h>

using namespace std;

int operator^(int, int); // line 6    
int main(int argc, char * argv[]) { /* ... */ }

int operator^(int a, int n)   // line 21
{
  return pow(a,n);
}

Compiler (I used g++ on Linux) returned me these errors:

main.cpp:6:23: error: ‘int operator^(int, int)’ must have an argument of class or enumerated type main.cpp:21:27: error: ‘int operator^(int, int)’ must have an argument of class or enumerated type

2
As codaddict says, you can't overload operators on built-in types, but even if you could, you might well not want to. ^ as bitwise xor is left-associative, so 2^3^4 would mean (2^3)^4 = 4096, rather than the more usual 2^(3^4) ~= 2.4E24. - Philip C
@PhilipC: if you're talking about powers, writing 2^3^4 without brackets is a bad idea no matter what the associativity is. Every coder that doesn't know associativity rules by heart will doubt what it actually does. - KillianDS
Oh... It's one of the main rules in operators overloading and I forgot about it. What a fail :/ - Kacper Kołodziej
@KillianDS True, but if you were going to make an assumption about which way it was intended, you'd probably assume in the wrong direction. - Philip C

2 Answers

9
votes

You cannot overload an operator to operate only on built-in types.

At least one of the arguments must be a user-defined class or enumerated type (or a reference to one of those) as clearly stated in the compiler error message.

6
votes

I tried to overload operator^ to make exponentiation easier and faster

You misspelled confusing, because it certainly isn't faster nor easier. Anyone maintaining your code will hate you if you did this.

Fortunately, C++ requires at least one parameter be a user-defined type, so you can't do this.