operator+ overloading

David Gillies daggillies at gmail.com
Thu Jan 12 14:39:05 CET 2012

On Wed, Jan 11, 2012 at 5:45 PM, Hans Aberg <haberg-1 at telia.com> wrote:
> On 11 Jan 2012, at 15:54, Slava Feshchenko wrote:
>> 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+.
> ...
> The type should normally be
>  A operator+(const A&, const A&);
> for this and other arithmetic operators, as the arguments are not modified. If you put the function definition in the header and inline, it will normally be removed, and if not, the copying of the temporary will go away by return value optimization.
> There is a GMP C++ wrap you might look at (see manual). And if you so like, I can send you a C++ wrap I have made.

Many moons ago, long before the standard C++ binding for GMP, I cooked
up a binding of my own for doing quick-and-dirty test harnesses etc.
Here's a skeleton, which you should be able to adapt for your purpose:


class CMPInteger
   CMPInteger(){mpz_init(&mpz);} // ctors
   CMPInteger(const CMPInteger& mp);
   CMPInteger(const unsigned long ul);

   CMPInteger&	operator=(const CMPInteger& mp); // assignment
   CMPInteger&	operator=(const unsigned long ul);

   CMPInteger&	operator+=(const CMPInteger& mp); // addition assignment
   CMPInteger&	operator+=(const unsigned long ul);

   MP_INT		mpz;		

CMPInteger operator+(const CMPInteger& mp1,const CMPInteger& mp2);
CMPInteger operator+(const CMPInteger& mp,const unsigned long ul);
CMPInteger operator+(const unsigned long ul,const CMPInteger& mp);


inline CMPInteger::CMPInteger(const CMPInteger& mp)

inline CMPInteger::CMPInteger(const unsigned long ul)

inline CMPInteger& CMPInteger::operator=(const CMPInteger& mp)
	return *this;

inline CMPInteger& CMPInteger::operator=(const unsigned long ul)
	return *this;
inline CMPInteger& CMPInteger::operator+=(const CMPInteger& mp)
	return *this;

inline CMPInteger& CMPInteger::operator+=(const unsigned long ul)
	return *this;

CMPInteger operator+(const CMPInteger& mp1,const CMPInteger& mp2)
	CMPInteger		temp=mp1;
	return temp+=mp2;

CMPInteger operator+(const CMPInteger& mp,const unsigned long ul)
	CMPInteger		temp=mp;
	return temp+=ul;

CMPInteger operator+(const unsigned long ul,const CMPInteger& mp)
	CMPInteger		temp=ul;
	return temp+=mp;

Note that only the compound assignment operator is a member function.
Also note how similar are the constructors and assignment operators.

Hope this helps.

David Gillies
San Jose
Costa Rica

More information about the gmp-discuss mailing list