Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Assignment Operator - Object Oriented Programming - Lecture Slides, Exercises of Object Oriented Programming

Assignment operator, Return Type, Parameter, Return type is String, Self Assignment problem, Modify the operator, Primitive types, Other Binary operators, Data vulnerability are points you can learn in this Object Oriented Programming lecture.

Typology: Exercises

2011/2012

Uploaded on 11/09/2012

bacha
bacha 🇮🇳

4.3

(41)

215 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 - Object Oriented Programming - Lecture Slides and more Exercises Object Oriented Programming in PDF only on Docsity!

Object-Oriented Programming

(OOP)

Lecture No. 18

  • Modifying:

class String{

public:

void operator =(const String &);

int main(){

String str1(“ABC");

String str2(“DE”), str3(“FG”);

str1 = str2; // Valid…

str1 = str2 = str3; // Error…

return 0;

}

  • str1=str2=str3 is resolved as:

str1.operator=(str2.operator=

(str3))

Return type is

void. Parameter

can’t be void

String & String :: operator = (const String & rhs){

size = rhs.size;

delete [] bufferPtr;

if(rhs.size != 0){

bufferPtr = new char[rhs.size+1];

strcpy(bufferPtr,rhs.bufferPtr);

}

else bufferPtr = NULL;

return *this;

}

void main(){

String str1(“AB"); String str2(“CD”), str3(“EF”); str1 = str2; str1 = str2 = str3; // Now valid…

}

int main(){

String str1("Fakhir");

// Self Assignment problem…

str1 = str1;

return 0;

}

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

  • Result of str1 = str

str

Fakhir

  • Now self-assignment is properly handled:

int main(){

String str1("Fakhir");

str1 = str1;

return 0;

}

  • Solution: modify the operator= function

as follows:

class String{

public:

const String & operator=

(const String &);

But we can do the following with

primitive 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;