Overloaded << and >> - Why Friend, Help

T

TJ

Hi,

I've been referring to many codes and books and always see that the
stream insertion operators are overloaded as friends. Why is that?
Are there any other overloading that need the same type of
specification, as friends in the class that will use them?

Thanks,

TJ
 
I

Ingo Nolden

Hi,

if you can not efficiently extract the data to be inserted from the class which is on the right sode of the op from
public members you need to access the private ones. In this case you need to be the class' friend.



TJ <>
 
A

Andre Kostur

TJ said:
Hi,

I've been referring to many codes and books and always see that the
stream insertion operators are overloaded as friends. Why is that?
Are there any other overloading that need the same type of
specification, as friends in the class that will use them?

It's not strictly required. What's probably happening is that the
streaming operators require access to private members of the class in order
to stream that class in/out.
 
D

David Harmon

I've been referring to many codes and books and always see that the
stream insertion operators are overloaded as friends. Why is that?

This and several related issues are covered in section 15 of Marshall
Cline's C++ FAQ. It is always good to check the FAQ before posting.
You can get the FAQ at:
http://www.parashift.com/c++-faq-lite/

I disagree quite a bit with the FAQ on this. I like the public member
"printon()" function and standalone non-friend inline operator>>().
printon() may or may not be virtual, as your requirements dictate, but
most often it probably is. The claim that people are not supposed to
call printon() is baloney.

Take your choice.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top