Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is friend ostream

Tags:

c++

I'm a bit confused about what exactly this line of code means in my header file.

friend ostream & operator << (ostream &, const something &);

Can someone clarify for me?

like image 399
user3304578 Avatar asked Feb 24 '14 18:02

user3304578


2 Answers

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.

like image 96
KRUKUSA Avatar answered Sep 28 '22 15:09

KRUKUSA


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.

like image 22
Corley Brigman Avatar answered Sep 28 '22 15:09

Corley Brigman