Firstly, yes. By accepting the std::ostream& parameter, you can also output to any derived stream, for example std::ofstream or std::cout , std::cerr .
Using operator<< , you can use this operator. Consider:
mystack<int> stackOfInts; //... std::cout << "Stack contents:" << std::endl << stackOfInts << std::endl;
This is simply more idiomatic than a โstandardโ function call.
Returning a stream allows you to bind an operator, as in the above example. The chain effectively passes the result of calling operator<< to another:
operator<<( operator<<("Stack contents:", std::endl), stackOfInts ) );
If this overloaded call also does not return std::ostream& , then there is no way to do:
operator<<( resultOfAbove, std::endl );
Declaring a friend function allows its definition to use private members. Without this, you will have to do something like writing a public recipient for each private member.
source share