
















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
The concept of binary operator overloading in object- oriented programming (oop) using the example of the complex class. It explains how to overload the '+' operator, handle addition of a complex number with a real number, and avoid memory leaks in string assignment.
Typology: Slides
1 / 24
This page cannot be seen from the preview
Don't miss anything!

















operator
+(const Complex
&^ rhs);
,^ c1.operator+(c2) In^ c2+c
,^ c2.operator+(c1)
operator+(constComplex
&^ rhs);
Complex
operator+(constdouble&
rhs);
rhs){
Complex t;t.real = real + rhs;t.img = img;return t;}
450.120 + c1; ►The + operator is called with reference to 450.120 ►No predefined overloaded + operator isthere that takes
Complex
as an argument
real^
or vice versa:
Class Complex{… friend Complex operator + (constComplex & lhs, const double &
rhs);
friend Complex operator + (constdouble & lhs, const Complex & rhs);}
Complex
operator
+^ (const
double
lhs, const
Complex
&^ rhs){
Complex
t; t.real
=^ lhs
+^ rhs.real; t.img
=^ rhs.img; return
t; }
Complex &);
friend Complex operator + (const
Complex &, const double &); friend Complex operator + (const
double &, const Complex &); };
String{int^ size;char^ *^ bufferPtr;public:String();String(char
*); String(const
String
&); … };
size = strlen(ptr);bufferPtr = new char[size+1];strcpy(bufferPtr, ptr);} else{bufferPtr = NULL; size = 0; } }
Member wisecopy assignment
str1 = str
(memory leak)