C++: << for Your Classes


The << operator is defined for standard C++ types, like int, float, etc. When you create your own class you typically need to redefine << to output objects of that class. This is possible in C++ thanks to overloading, which allows the same function/operator to be defined for different types of data. As the object to be output is the righthand operand of << it cannot be a member function of your class (it's a C++ restriction that it must be the lefthand operand in order to overload the operator as a member function). At the same time your overloaded operator typically needs to access the private data in your object. Therefore the overloaded operator has to be declared as a friend of your class. To do this, in your class header file before any public or private parts, declare the overloaded operator like this:
friend ostream &operator <<(ostream &OutputStream,const YourClassName &TheObject);
and in the implementation file for the class you implement the overloaded operator something like this:
ostream &operator <<(ostream &OutputStream,const YourClassName &TheObject) {

OutputStream << TheObject.PrivateData;

return(OutputStream);
}
Of course your implementation can do more than simply output the private data.