Santosh Sahu
Santosh Sahu

Reputation: 2244

which "<<" operator function should be used?

There are two ways of implementing operator "<<" or ">>" function in a project.

1.As a non-member function

2.As a friend

  #include<iostream>
  using namespace std;
  class xxx{
     private: int x;
     public: xxx(int val=0):x(val){}
              int getx(){return x;}
             friend ostream& operator <<(ostream& o, xxx& x1);
  };
  ostream& operator<<(ostream& o, xxx& x1)
  {
    o<<x1.getx();
    return o;
  }
  ostream& operator <<(ostream& o, xxx& x1)
  {
     o<<x1.getx();
     return o;
  }
  int main(int argc, char *argv[])
  {
     xxx x1(5);
     return 0;
  }

Looks like both non-member and friend function have same signature when implementing, and thus i get compiler error : "error: redefinition of 'std::ostream& operator<<(std::ostream&, xxx&)' ".

Could anyone please help how to compile the above code.

Also would like to know in which situation should we use non-member "operator =" function over friend "operator =" function.

Upvotes: 1

Views: 77

Answers (2)

Chris Dodd
Chris Dodd

Reputation: 126203

You seem to be confused -- a friend function is a non-member function. So your friend declaration declares the non-member function and makes it a friend. You then define the (non-member) function twice, which is an error.

The two ways to define (most) overloaded operators is as a member function or a non-member function. You cannot do both for the same operator, and if you define it as a non-member, it may be a friend or not as you prefer (friend is irrelevant)

As for your final question -- you cannot define operator= as a non-member function. It must be a member function. friend is irrelevant.

Upvotes: 2

DrWatson
DrWatson

Reputation: 418

The two definitions are identical. And in your case, the operator is not accessing private or protected members of the class, so the friend declaration is redundant.

Upvotes: 1

Related Questions