



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Advanced topics in c++ programming, specifically operator overloading using friend functions and the overloading of input and output operators. The limitations of using member functions for operator overloading and introduces friend functions as a solution. It also provides examples of overloading the insertion and extraction operators for a complex number data type.
Typology: Slides
1 / 5
This page cannot be seen from the preview
Don't miss anything!




E.g., class complex_number {
Usman Younis
private: //private data public: complex_number operator + (const complex_number& number); };
Operator Overloading (contd..)
E.g., complex_number N1; cout<<N1; The compiler will interpret it as cout.operator<<(N1)
Usman Younis
Overloading using Friends
class complex_number { private: //private data
Usman Younis
public: friend complex_number operator + (complex_number& number1, complex_number& number2 ); };
Overloading I/O
Extraction:
Insertion:
Usman Younis
Overloading I/O (contd..)
Example: class complex numberp _ { private: double real_part; double imag_part;
public: complex number(double a double b): real part(a) imag part(b)
Usman Younis
complex_number(double a, double b): real_part(a), imag_part(b) { } friend void operator>>(istream& in, complex_number& N); friend void operator<<(ostream& out, complex_number& N); };
Overloading I/O (contd..)
void operator>>(istream& in, complex_number& N) { cout<<“Enter a complex number (real part, imaginary part) : ”; cout<<endl;
in>>N.real_part>>N.imag_part; }
void operator<<(ostream& out, complex_number& N)
Usman Younis
p ( , p _ ) { out<<“Complex number is : ”<<endl <<N.real_part<<“ + i”<<N.imag_part<<endl; }
Overloading I/O (contd..)
void main() {{ complex_number cNumber;
cin>>cNumber; //compiler’s interpretation is //operator>>(cin, cNumber);
Usman Younis
cout<<cNumber; //compiler’s interpretation is //operator<<(cout, cNumber); }