free function or member function for overloading += operator?

P

PengYu.UT

Hi,

I have the following two programs. One is to overload += as a free
function, the other is to overload += as a member function. Both of
them works fine.

I'm wondering which one I should choose in practice. What are the pros
and cons for these two implementations?

Thanks,
Peng


$ cat main_free.cc
#include <iostream>

class Integer {
public:
Integer(int i) : _i(i) {}
friend Integer &operator+=(Integer &, int);
friend std::eek:stream &operator<<(std::eek:stream &, const Integer &);
private:
int _i;
};

Integer & operator+=(Integer & I, int i) {
I._i += i;
return I;
}

std::eek:stream &operator<<(std::eek:stream &os, const Integer &I) {
os << "Integer: " << I._i;
return os;
}

int main ()
{
Integer I(0);
std::cout << I << std::endl;
I += 10;
std::cout << I << std::endl;
}


$ cat main_member.cc
#include <iostream>

class Integer {
public:
Integer(int i) : _i(i) {}
Integer &operator+=(int i) {
_i += i;
return *this;
}
friend std::eek:stream &operator<<(std::eek:stream &, const Integer &);
private:
int _i;
};


std::eek:stream &operator<<(std::eek:stream &os, const Integer &I) {
os << "Integer: " << I._i;
}

int main ()
{
Integer I(0);
std::cout << I << std::endl;
I += 10;
std::cout << I << std::endl;
}


$ ./main_free.exe
Integer: 0
Integer: 10
$ ./main_member.exe
Integer: 0
Integer: 10
 
V

Victor Bazarov

I have the following two programs. One is to overload += as a free
function, the other is to overload += as a member function. Both of
them works fine.

I'm wondering which one I should choose in practice. What are the pros
and cons for these two implementations?
[..]

A general rule: if the operator modifies the object, it should be
implemented as a member. I have no comment beyond that.

V
 
M

Marcus Kwok

Hi,

I have the following two programs. One is to overload += as a free
function, the other is to overload += as a member function. Both of
them works fine.

I'm wondering which one I should choose in practice. What are the pros
and cons for these two implementations?

One common idiom is to implement += as a member, and + as a free
function written in terms of +=. For example (untested):

Integer& Integer::eek:perator+=(const Integer& rhs)
{
_i += rhs._i;
return *this;
}

Integer operator+(const Integer& lhs, const Integer& rhs)
{
Integer temp(lhs);
lhs += rhs;
return temp;
}

I seem to remember that this idiom allows for conversions to take place
on the left operands for operator+. I'm not sure if there are any other
technical advantages to this approach though.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top