0

i know how to overload operator += if i am using a class for e.g.

class temp
{
public:
    int i;
    temp(){ i = 10; }
    int operator+=(int k)
    {
           return i+=k;
    }
};
int main()
{
    temp var;
    var += 67;
    cout << var.i;
    return 0;
}

But why cant i create a overloaded += function for basic datatype

int operator+=(int v, int h)
{
    return  v += (2*h);
}
int main()
{
    int var = 10;
    var += 67;
    cout << i;
    return 0;
}

i am getting error when i am compiling the above overloaded function.

lsrawat
  • 157
  • 3
  • 9
  • [You cannot change the meaning of operators for built-in types in C++, operators can only be overloaded for user-defined types. That is, at least one of the operands has to be of a user-defined type.](http://stackoverflow.com/a/4421715/445976) – Blastfurnace Jul 11 '15 at 05:05

2 Answers2

2

It's not allowed to overload operators for primitive types. For reference see it written here:

http://www.cprogramming.com/tutorial/operator_overloading.html

Yet, you can have a similar effect by creating a "wrapper" class around the primitive type you want to overload and then creating a "conversion constructor" to go from the primitive type to your custom class and another "conversion operator" to go from your wrapper custom type back to the primitive type.

For you temp class something like this:

class temp
{
public:
    int i;
    temp(const int& orig){ i = orig; }
    operator int(void) const { return i; }
    int operator+=(int k)
    {
           return i+=k;
    }
};
Rudi Cilibrasi
  • 885
  • 4
  • 12
1

Operator overloading is not supported for primitive types. These operations are performed by direct CPU instructions. This is probably for a good reason though, as code that overloads basic arithmetic functions would be impossible to maintain.

Erik Godard
  • 5,930
  • 6
  • 30
  • 33