lsrawat
lsrawat

Reputation: 157

C++ increment ++ operator overloading

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.

Upvotes: 0

Views: 78

Answers (2)

Erik Godard
Erik Godard

Reputation: 6030

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.

Upvotes: 1

Rudi Cilibrasi
Rudi Cilibrasi

Reputation: 885

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;
    }
};

Upvotes: 2

Related Questions