Assignment Operator and Operator Overloading in Object-Oriented Programming, Exercises of Object Oriented Programming

The concept of assignment operator and its implementation in a string class in object-oriented programming (oop). It also covers the topic of operator overloading, focusing on the + operator and its various definitions for complex numbers. The implications of friend functions and their limited use in encapsulation.

Typology: Exercises

2011/2012

Uploaded on 08/08/2012

anchita
anchita 🇮🇳

4.4

(7)

113 documents

1 / 25

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Object-Oriented Programming
(OOP)
Lecture No. 18
docsity.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19

Partial preview of the text

Download Assignment Operator and Operator Overloading in Object-Oriented Programming and more Exercises Object Oriented Programming in PDF only on Docsity!

Object-Oriented Programming

(OOP)

Lecture No. 18

Assignment operator ►Modifying:^ class String{

… public:… void operator =(const String &);};

Assignment operator^ int main(){

String str1(“ABC");String str2(“DE”), str3(“FG”);str1 = str2;

// Valid…

str1 = str2 = str3;

// Error…

return 0;}

Assignment operator ►str1=str2=str

is resolved as:

str1.operator=(str2.operator=

(str3))

Return type isvoid. Parametercan’t be void

Assignment operator String

&^ String

::^

operator

=^ (const

String

rhs){

size

=^ rhs.size; delete

[]^

bufferPtr; if(rhs.size

!=^

bufferPtr

=^ new

char[rhs.size+1];

strcpy(bufferPtr,rhs.bufferPtr);} else^ bufferPtr

=^ NULL;

return

*this;

Assignment operator^ void

main(){String

str1(“AB"); String

str2(“CD”),

str3(“EF”);

str

=^ str2; str

=^ str

=^ str3;

Now

valid…

Assignment operator^ int

main(){String

str1("Fakhir");

//^

Self

Assignment

problem…

str

=^

str1;

return

… // size = rhs.size;// delete [] bufferPtr;…

Assignment operator ►Result of

str1 = str1 str

Fakhir

Assignment operator ►Now self-assignment is properly handled:^ int

main(){String

str1("Fakhir");

str

=^

str1;

return

Assignment operator ►Solution: modify the

operator=

function as follows:^ class String{

… public:… const

String & operator=

(const String &);

Assignment operator^ But we can do the following withprimitive types:^ int main(){

int a, b, c;(a = b) = c;return 0;}

Other Binary operators^ ►Overloading

operator:

class Complex{double real, img;public:Complex & operator+=(const Complex &

rhs);

Complex & operator+=(count double &

rhs);

Other Binary operators^ Complex & Complex::operator +=

(const double & rhs){

real = real + rhs;return * this;}

Other Binary operators^ int main(){

Complex c1, c2, c3;c1 += c2;c3 += 0.087;return 0;}