You are here:

C++/overloading operator in c++


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;
  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;
  return 0;

Thanks in advance,

> 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() << '}' ; }  


All Answers

Answers by Expert:

Ask Experts




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.


about 15 years or so

post graduate engineer

©2017 All rights reserved.