Docsity

Binary Operators - Object Oriented Programming - Lecture Slides, Slides of Object Oriented Programming

Partial preview of the text

Download Binary Operators - Object Oriented Programming - Lecture Slides and more Slides Object Oriented Programming in PDF only on Docsity!

Object-Oriented Programming

(OOP)

Lecture No. 17

  • Overloading + operator:

class Complex{ private: double real, img; public: …

Complex operator +(const Complex & rhs); };

  • The return type is Complex so as to facilitate complex statements like:

Complex t = c1 + c2 + c3;

  • The above statement is automatically converted by the compiler into appropriate function calls:

(c1.operator +(c2)).operator +(c3);

  • The binary operator is always called

with reference to the left hand

argument

  • Example:
    • In c1+c2, c1.operator+(c2)
    • In c2+c1, c2.operator+(c1)
  • Modifying the complex class:

class Complex{

...

Complex operator+(const Complex & rhs);

Complex operator+(const double& rhs);

};

Complex operator + (const double& rhs){ Complex t; t.real = real + rhs; t.img = img; return t;

}

  • But problem arises if we do the following:

Complex c5 = 450.120 + c1;

  • The + operator is called with reference to
  • No predefined overloaded + operator is there that takes Complex as an argument
  • Now if we write the following two functions to the class, we can add a Complex to a real or vice versa:

Class Complex{

… friend Complex operator + (const Complex & lhs, const double & rhs); friend Complex operator + (const double & 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;

}

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 wise copy assignment

Assignment operator

  • Result of str1 = str2 (memory leak)

str

Hello

str

World