jsan
jsan

Reputation: 1057

How to overload operator -= C++

I need to overload the assignment/decrement operator (-=) so that the code

object -= int

decrements object.life class member by the value on the rhs. Here is my code:

const Object& Object::operator -= (const Object& obj)
{ 
    if (life == obj.life)`
    {   
        this->life -= obj.life;
        return *this;
    }
} 

How do I implement this in my main?

int main()
{ 
    Object o1;
    o1 -= 5; //DOESN'T WORK
}

Any suggestions? Thanks

Upvotes: 1

Views: 1020

Answers (3)

Rahul Tripathi
Rahul Tripathi

Reputation: 172458

YOu can try using this:-

const Object& Object::operator-= (int x)

since overload should take int

Upvotes: 0

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361482

The overload should take int, not Object:

Object& Object::operator -= (int amount);

Or, alternatively, if it makes sense, you could write a constructor that takes an int to allow implicit conversion from int to Object type. The argument should be used to initialize life.

Upvotes: 3

Xymostech
Xymostech

Reputation: 9850

You're overloading the case when you subtract an object from an object, but the example you show is subtracting an integer. I you want to overload the operator that takes an integer:

const Object& Object::operator-= (int x);

Upvotes: 7

Related Questions