Docsity

Binary Operator Overloading in Object-Oriented Programming, Slides of Object Oriented Programming

Partial preview of the text

Download Binary Operator Overloading in Object-Oriented Programming and more Slides Object Oriented Programming in PDF only on Docsity!

Object-Oriented Programming

(OOP)

Lecture No. 17

Binary operators ►Overloading + operator: class Complex{private:double real, img;public:… Complex

operator

+(const Complex

&^ rhs);

Binary operators ►The return type is Complex so as tofacilitate complex statements like: Complex t = c1 + c2 + c3; ►The above statement isautomatically converted by thecompiler into appropriate functioncalls: (c1.operator +(c2)).operator+(c3);

Binary operators ►The binary operator is always calledwith reference to the left handargument ►Example: In^ c1+c

,^ c1.operator+(c2) In^ c2+c

,^ c2.operator+(c1)

Binary operators ►Modifying the complex class: class^ Complex{...Complex

operator+(constComplex

&^ rhs);

Complex

operator+(constdouble&

rhs);

Binary operators Complex operator + (const double&

rhs){

Complex t;t.real = real + rhs;t.img = img;return t;}

Binary operators ►But problem arises if we do the following: Complex c5 =

450.120 + c1; ►The + operator is called with reference to 450.120 ►No predefined overloaded + operator isthere that takes

Complex

as an argument

Binary operators ►Now if we write the following twofunctions to the class, we can add a Complex^ to a

real^

or vice versa:

Class Complex{… friend Complex operator + (constComplex & lhs, const double &

rhs);

friend Complex operator + (constdouble & lhs, const Complex & rhs);}

Binary operators

Complex

operator

+^ (const

double

lhs, const

Complex

&^ rhs){

Complex

t; t.real

=^ lhs

+^ rhs.real; t.img

=^ rhs.img; return

t; }

Binary operators Class Complex{… Complex operator + (const

Complex &);

friend Complex operator + (const

Complex &, const double &); friend Complex operator + (const

double &, const Complex &); };

Assignment operator ►Consider a string class:^ class

String{int^ size;char^ *^ bufferPtr;public:String();String(char

*); String(const

String

&); … };

Assignment operator^ String::String(char * ptr){if(ptr != NULL){

size = strlen(ptr);bufferPtr = new char[size+1];strcpy(bufferPtr, ptr);} else{bufferPtr = NULL; size = 0; } }

Assignment operator int main(){String str1(“Hello");String str2(“World”);str1 = str2;return 0;}

Member wisecopy assignment

Assignment operator ►Result of

str1 = str

(memory leak)

Hello^ str

World str