Click to See Complete Forum and Search --> : <<,>> operators


contactsatish
February 20th, 2002, 04:24 AM
Why should &gt;&gt; , &lt;&lt; operators which are over loaded be a friend functions.

Graham
February 20th, 2002, 04:34 AM
They don't have to be. What they must be are free functions (i.e. not member functions). These operators have to have the stream as their left-hand argument, and the only way you can do that with a member function is to make it a member of the stream class. This is obviously impossible, so you make them free functions supplied with your class.

You can avoid friendship by supplying a (public) method in your class that does the work, then calling that from operator&lt;&lt; and operator&gt;&gt;

class A
{
public:
ostream& writeTo(ostream&);
istream& readFrom(istream&);
private:
// data
};

ostream& operator&lt;&lt;(ostream& s, A& a)
{
return a.writeTo(s);
}

istream& operator&gt;&gt;(istream& s, A& a)
{
return a.readFrom(s);
}




He who breaks a thing to find out what it is, has left the path of wisdom - Gandalf

NMTop40
February 20th, 2002, 04:35 AM
you can overload an operator in your class, but only when your own class is the LHS and the 'parameter' is the RHS.

But when making your class streamable, the stream is on the LHS. Thus:

ostream os;
os &lt;&lt; myObject;
istream is;
is &gt;&gt; myObject;




Thus you cannot overload the operator within the class, but must use an external function like this:

ostream& operator &lt;&lt;( ostream& os, const MyClass& myobject );
istream& operator &gt;&gt;( istream& is, const MyClass& myobject );



These function do not need to be a friend unless they access private members of MyClass. As MyClass is your own, you can always arrange for that not to be the case, my allowing them to simply call a member function that takes ostream& or istream& as a parameter.

There is, however, nothing wrong with using friend in this instance, as it is part of the interface of the class.


The best things come to those who rate

NMTop40
February 20th, 2002, 05:48 AM
of course (in my above post) the istream one should not use a const reference!



The best things come to those who rate

contactsatish
February 20th, 2002, 06:19 AM
That answers my question thanks so lot

contactsatish
February 20th, 2002, 06:19 AM
thank you