I\'m a bit confused about what exactly this line of code means in my header file.
friend ostream & operator << (ostream &, const something &
That line of code says that the operator << is a friend of something (since it's listed in the something class definition). This means that that operator << function can access the variables inside there.
The & here as the parameters mean that you pass in objects when calling the method and those parameters will just be another name for those parameter objects. Returning ostream & means that you're going to return the ostream parameter so that you can connect << expressions together avoiding creating a new "cout" when using the one global cout is what is needed.
The friend
keyword can name either functions or entire classes. In either case, it means that the implementation of the named function, or the named class, is allowed to access private
and protected
members of the class in which the friend
declaration appears.
In this case, it means that this particular overload of the operator<<
function is allowed to access internals of the something
class, in order to write then to an output stream such as std::cout
.
As mentioned in many places, friend
is a bypass to the normal protection mechanisms of C++ - it allows the function in question to access protected/private members, which normally only class members can do.
You'll often seen operators declared friends, because operators are never inside the class itself, but often need to modify something in the class and/or access private information. I.E. you may not want an external function to be able to muck with your internal pointers etc, but you may want to be able to print them out for status etc. You don't see them used very often otherwise - technically, it breaks encapsulation - but operators are kind of a special case.
A C++ class
may declare another class or a function to be a friend
. Friendly classes and methods may access private members of the class. So, the free operator method <<
, not defined in any class, may insert something
s into a stream and look at and use the private members of something
to do its work. Suppose something
were complex
:
class complex {
private:
double re;
double im;
public:
complex(double real = 0.0, double imag = 0.0) : re(real), im(imag) {}
friend ostream & operator<<(ostream& os, complex& c);
};
ostream & operator<<(ostream& os, complex& c){
os << c.re << std::showpos << c.im;
return os;
}