operator+ overloading

Slava Feshchenko slavaf2000 at gmail.com
Wed Jan 11 15:54:40 CET 2012


I am building a class (called Money)  for handling monetary values and use
GNU MP as a back end for the calculations. I can't seem to be able to
overload operator+. I want very straight forward behavior:

Money a;
Money b;
Money c;

.... (set a and b to some values)

c = a + b; //this should set c to the sum of a and b and leave a and b
unmodified

The Money class has a private data member declared as follows:

mpz_t monetaryUnit;

which maintains the amount of money in cents. So operator+ would be summing
the values maintained in this variable and assigning it to c.monetaryUnit.
I already overloaded operator= and it works as expected. The Money class
has a constructor which calls mpz_init(monetaryUnit) and a destructor,
which calls mpz_clear(monetaryUnit);

The broken code for operator+ is as follows:

Money & Money::operator+(Money &m)
{
Money temp;
mpz_add(temp.monetaryUnit, this->monetaryUnit, m.monetaryUnit);
return temp;
}

In debug mode, this seems to work until the return statement. The code
correctly sums the values and assign the result to temp.monetaryUnit; Then
after the return statement, the destructor is called for the object temp,
which calls mpz_clear(monetaryUnit). After this call, the value in
temp.monetaryUnit is something ridiculous like 123198732346827429374
(instead of the sum of a and b). And this is the value that gets assigned
to c in the end. What am I missing? What's wrong with my destructor if
that's where the issue is? Please help!!

If you need more details on the implementation, please let me know. Also
note that I typed the code above right in the email, and not copied from
the actual source code... so please ignore any syntax issues.

Sincerely,

SF


More information about the gmp-discuss mailing list