You are here:

C++/overloading operator in c++

Advertisement


Question
Hi Vijayan,
         i tried overloading << operator. it gave me compilation error for following code.
  ostream& operator <<(ostream &ptr,sample &s)
  {
     ptr << s.l << s.b;
     return ptr;
  }
But it is successful after making this as friend to the sample class. my question is....1) Is it mandatory to keep overloading operator functions as friend . If so, for what other operators it is applicable.

/* pasting complete code for better understanding */
#include "iostream"
using namespace std;

class sample
{
  int l;
  int b;
public:
  sample(int i=0,int j=0)
  {
     l = i;
     b = j;
  }
  friend ostream& operator <<(ostream &ptr,sample &s)
  {
     ptr << s.l << s.b;
     return ptr;
  }
};

int main()
{
  sample s1;
  cout<<s1;
  cin.get();
  return 0;
}


Thanks in advance,
Bhupal.

Answer
> Is it mandatory to keep overloading operator functions as friend.

No, it is not. Overloading operators via free functions and declaring a function as a friend are orthogonal issues.

You would need to make the free function that overloads an operator a friend function if and only if it needs access to non-public members of the class.

For example:

struct A
{
   int i ;
   int value() const { return j ; }

   private: int j ;

   // ...
};  

inline std::ostream& operator<< ( std::ostream& stm, const A& a )
{ return stm << "A{" << a.i << ',' << a.value() << '}' ; }  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.