0

I have created a custom BigInt class and overrode the + operator to add two objects of this class. But why does C++ asks me to override the shorthand notation += as well? And for some reason the shorthand notation doesn't work as expected even if I do override it. What's wrong here?

class BigInt {
        string num;
       
        public:
        string number() {
            return num;
        }
        BigInt(string n):num(n) {}
        BigInt operator+(BigInt o) {
            string result;

            // logic for adding but not relevant here

            return BigInt(result);
        }
        BigInt operator+=(BigInt o) {
            return *this+o;
        }
    };

from another function for example:

BigInt a(num1);
BigInt b(num2);

a+=b; // doesn't works; it adds but doesn't assign the result back to a
a=a+b; // works; adds as well as result is assigned to a
Chirag Arora
  • 877
  • 1
  • 9
  • 22
  • "it adds but doesn't assign". That's because **you** don't assign. `operator+=` should modify `*this` and that's the programmer's responsibility to make it happen. – n. m. could be an AI Aug 09 '21 at 10:49
  • `a += b;`. Do you expect `a` to be modified? Of course you do. But your `operator+=` overload does not modify its object. And it returns a temporary object. Do you expect `a += b` to result in a temporary object? Nope. The shown code implements these operators backwards. Usually it's the `+=` that implements the actual addition operator, and `+` calls it, and not the other way around. – Sam Varshavchik Aug 09 '21 at 10:49
  • Yep understood my mistake. Thanks! The `+=` should modify the contents of the current object. I believed `a+=b` gets translated to `a=a+b`. But this is the first time I am trying low level stuff so learning new things. – Chirag Arora Aug 09 '21 at 11:00
  • @ChiragArora -- for built-in types, `a += b` gets translated to `a = a + b`. But for user-defined types there is no connection between the two operations. `operator+` is a function that gets called for `a + b`, and `operator+=` is a function that gets called for `a += b`. – Pete Becker Aug 09 '21 at 14:59

0 Answers0