+91 9945200008     support@uttaracomputers.com

Why not "operator>>" and "operator<<" be friends of class complex ?


Dear Sir, first of all I would like to thank you for providing wonderful C++ & OOPS discussions as part of the C++ Audioware.

I am so happy to learn C++ from your discussions.

I’ve few queries, which I ask one by one.

Q) Why not “operator>>” and “operator<<” be friends of class complex ?

In audio 04a 17:10 frame, you’ve said

“operator << and operator >> can’t be friends as we’re writing class complex today, they can only be global functions”

I didn’t understand this statement, as we can make them as friends of class complex and provide them as part of Interface to perform read and write operations on objects of class complex.

Requesting to answer whenever you’re comfortable. I am happy to hear from you.

Yours Sincerely,

Shakthi Prashanth


  • You must to post comments

Operator << needs class ostream object ( like cout ) as first parameter;  Operator >> needs class istream object ( like cin ) as first parameter; Hence these functions like operator<< and operator>> cannot be declared today as friends of ostream / istream classes.  Friends of a class must be declared at the time the class is defined.

In addition, a member function always needs a pointer to an implicit object of this class ( “this” pointer ) as the first parameter.  Since the functions that we need to define for operators << and >> for class complex need pointer to ostream / istream as first parameter, they cannot be friends / members of class complex.  They must be global functions.

MLS Shastry

  • m.shakthi.prashanth@gmail.com
    Thank you for the answer sir.. I do agree that operator<> can’t be members of any class, but however they can be friends of a class. It is also confirmed from c++ reference: http://en.cppreference.com/w/cpp/language/operators I have tried making operator<< as friend of class complex to print complex numbers. friend ostream &operator<<(ostream &out, const Complex &c); It works!
  • You must to post comments
Showing 1 result
Your Answer

Please first to submit.