Because the << operator is not truly a part of the class since it is a universal operator and it will or may need access to protected and private data in the class. Declaring the operator as a friend grants it access.
@jwings - Why don't you just test it both ways.
Write a simple class and make the operator << a class member function, then do it as a friend functions and see what happens and how you would call the different overloads
and the differences are when you do a chained assignment ( a= b = c).
We cannot because the first operand of a member function is a poiner to object that is this. So in any case this operator function should be global. However we can provide a public interface that can be used inside this operator-function.
For example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
class myCllass
{
public:
myClass( int i = 0 ) : x( i ) {}
std::ostream & out( std::ostream & os ) const
{
return ( os << x );
}
private:
int x;
};
std::ostream & operator( std::ostream &os, const myClass &rhs )
{
return ( rhs.out( os ) );
}
In this case there is no need to declare function operator << as a friend of the class.
! was just trying to say - that at first you may be tempted to overload the << operator to output to a stream as part of a the class- but you will end up with something like this:
#include <iostream>
usingnamespace std;
class MyClass
{
public:
MyClass () :m_Val(99) {}
MyClass& operator << ( ostream& os) //is this what the return type should be??
{
os << m_Val;
return *this;
}
private:
int m_Val;
};
int main()
{
MyClass mc;
mc << cout; //weird
return 0;
}
Which is most unusual and not the way everybody would expect it to be done by convention
//============================================================
//============================================================
But if the class was the sort of class that could be used as a source and/or sink
of object _ like a link list, then you could overload the << and >> operators as class members to retrieve or insert objects in the list.
Example: