CSC241 Object-Oriented Programming (OOP) Lecture No. 10.

Slides:



Advertisements
Similar presentations
Operator overloading redefine the operations of operators
Advertisements

Operator Overloading. Introduction Operator overloading –Enabling C++’s operators to work with class objects –Using traditional operators with user-defined.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 8 - Operator Overloading Outline 8.1 Introduction 8.2 Fundamentals of Operator Overloading 8.3.
CSC241 Object-Oriented Programming (OOP) Lecture No. 9.
Class and Objects.
Rossella Lau Lecture 10, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 10: Operator overload  Operator overload.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 18 - C++ Operator Overloading Outline 18.1Introduction.
Class template Describing a generic class Instantiating classes that are type-specific version of this generic class Also are called parameterized types.
CS 117 Spring 2002 Classes Hanly: Chapter 6 Freidman-Koffman: Chapter 10, intro in Chapter 3.7.
Class Array template The array class defined in last week manipulate array of integer If we need to define class of array for float, double data type,
OOP Egar 2008 – Recitation 41 Object Oriented Programming Spring 2006 Recitation 6.
Operator overloading Object Oriented Programming.
Data Structures Using C++1 Chapter 2 Object-Oriented Design (OOD) and C++
1 Operator Overloading in C++ Copyright Kip Irvine, All rights reserved. Only students enrolled in COP 4338 at Florida International University may.
Object Oriented Programming in C++ Chapter5 Operator Overloading.
Overloading Operators. Operators  Operators are functions, but with a different kind of name – a symbol.  Functions.
Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
M. Taimoor Khan #include void main() { //This is my first C++ Program /* This program will display a string message on.
Operatorsand Operators Overloading. Introduction C++ allows operators to be overloaded specifically for a user-defined class. Operator overloading offers.
Operator overloading II
1 Streams In C++, I/O occurs in streams. A stream is a sequence of bytes Each I/O device (e.g. keyboard, mouse, monitor, hard disk, printer, etc.) receives.
1 Overloading Overloading allows a function or operator to have a different meaning depending on the type of objects it is used on. Examples: operator+
Operator Overloading Operator Overloading allows a programmer to define new uses of the existing C/C++ operator symbols. –useful for defining common operations.
Computer Science Department CPS 235 Object Oriented Programming Paradigm Lecturer Aisha Khalid Khan Operator Overloading.
Overloading Operator MySting Example. Operator Overloading 1+2 Matrix M 1 + M 2 Using traditional operators with user-defined objects More convenient.
CSC241 Object-Oriented Programming (OOP) Lecture No. 8.
CPSC 252 Operator Overloading and Convert Constructors Page 1 Operator overloading We would like to assign an element to a vector or retrieve an element.
Operator Overloading. Introduction It is one of the important features of C++ language  Compile time polymorphism. Using overloading feature, we can.
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Operator Overloading.
Slide 1 Chapter 8 Operator Overloading, Friends, and References.
Chapter 11 Friends and Overloaded Operators. Introduction to function equal // Date.h #ifndef _DATE_H_ #define _DATE_H_ class CDate { public: CDate();
LECTURE LECTURE 13 Operator Overloading Textbook p.203—216 Today: const member functions Overloading Operators Postfix/infix increment.
CS Object Oriented Programming Using C++
1 Today’s Objectives  Announcements Homework #3 is due on Monday, 10-Jul, however you can earn 10 bonus points for this HW if you turn it in on Wednesday,
1 More Operator Overloading Chapter Objectives You will be able to: Define and use an overloaded operator to output objects of your own classes.
Operator Overloading. Binary operators Unary operators Conversion Operators –Proxy Classes bitset example Special operators –Indexing –Pre-post increment/decrement.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 25 December 1, 2009.
Operator Overloading Moshe Fresko Bar-Ilan University Object Oriented Programing
Learning Objectives Fundamentals of Operator Overloading. Restrictions of Operator Overloading. Global and member Operator. Overloading Stream-Insertion.
Operator Overloading Chapter Objectives You will be able to Add overloaded operators, such as +,-, *, and / to your classes. Understand and use.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 26 Clicker Questions December 3, 2009.
1 CSC241: Object Oriented Programming Lecture No 08.
Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and Information Science,
Exercises on Polymorphism and Operator Overloading TCP1201: 8.
 Binary operators  Unary operators  Conversion Operators  Proxy Classes (simulating a reference) ▪ bitset example  Special operators  Indexing 
Operator Overloading What is operator overloading? Most predefined operators (arithmetic, logic, etc.) in C++ can be overloaded when applied to objects.
Operator Overloading.
Chapter 18 - C++ Operator Overloading
Object-Oriented Programming (OOP) Lecture No. 16
Andy Wang Object Oriented Programming in C++ COP 3330
Overloading C++ supports the concept of overloading Two main types
Object-Oriented Programming (OOP) Lecture No. 15
Introduction to Programming
Department of Computer and Information Science, School of Science, IUPUI Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI
CSC241: Object Oriented Programming
Object-Oriented Programming (OOP) Lecture No. 21
Object-Oriented Programming (OOP) Lecture No. 17
Object-Oriented Programming (OOP) Lecture No. 16
Jim Fawcett Copyright ©
Operator Overloading.
Object-Oriented Programming (OOP) Lecture No. 18
תכנות מכוון עצמים ו- C++ יחידה 06 העמסת אופרטורים
Object-Oriented Programming (OOP) Lecture No. 20
Introduction to Programming
Operator Overloading.
COP 3330 Object-oriented Programming in C++
Chapter 18 - Operator Overloading
Introduction to Programming
Jim Fawcett Copyright ©
Presentation transcript:

CSC241 Object-Oriented Programming (OOP) Lecture No. 10

Stream Insertion operator ► Often we need to display the data on the screen ► Example: int i = 1, j = 2; cout << "i = " << i << "\n"; cout << "j = " << j << "\n";

Stream Insertion operator Complex c1; cout << c1; cout << c1 << 2; // Compiler error: binary '<<' : no operator // defined which takes a right-hand // operand of type ‘ class Complex ’

Stream Insertion operator class Complex{ … public: … void operator << (const Complex & rhs); };

Stream Insertion operator int main(){ Complex c1; cout << c1; // Error c1 << cout; c1 << cout << 2; // Error return 0; };

Stream Insertion operator class Complex{ … public: … void operator << (ostream &); };

Stream Insertion operator void Complex::operator << (ostream & os){ os << '(' << real << ', ' << img << ')'; }

Stream Insertion operator class Complex{... friend ostream & operator << (ostream & os, const Complex & c); }; Note: this object is NOT const Note: return type is NOT const

Stream Insertion operator // we want the output as: (real, img) ostream & operator << (ostream & os, const Complex & c){ os << '(' << c.real << ', ' << c.img << ')'; return os; }

Stream Insertion operator Complex c1(1.01, 20.1), c2(0.01, 12.0); cout << c1 << endl << c2;

Stream Insertion operator Output: ( 1.01, 20.1 ) ( 0.01, 12.0 )

Stream Insertion operator cout << c1 << c2; is equivalent to operator<<(operator<<(cout, c1), c2);

Stream Extraction Operator ► Overloading “ >> ” operator: class Complex{... friend istream & operator >> (istream & i, Complex & c); }; Note: this object is NOT const

Stream Extraction Operator istream & operator << (istream & in, Complex & c){ in >> c.real; in >> c.img; return in; }

Stream Extraction Operator ► Main Program: Complex c1(1.01, 20.1); cin >> c1; // suppose we entered // for c1.real and // for c1.img cout << c1;

Stream Extraction Operator Output: ( , )

Other Binary operators ► Overloading comparison operators: class Complex{ public: bool operator == (const Complex & c); //friend bool operator == (const //Complex & c1, const Complex & c2); bool operator != (const Complex & c); //friend bool operator != (const //Complex & c1, const Complex & c2); … };

Other Binary operators bool Complex::operator ==(const Complex & c){ if ((real == c.real) && (img == c.img)){ return true; } else return false; }

Other Binary operators bool operator ==(const Complex& lhs, const Complex& rhs){ if ((lhs.real == rhs.real) && (lhs.img == rhs.img)){ return true; } else return false; }

Other Binary operators bool Complex::operator !=(const Complex & c){ if ((real != c.real) || (img != c.img)){ return true; } else return false; }

Other Binary operators ► We have seen the following string class till now: class String{ private: char * bufferPtr; int size; public: String(); String(char * ptr); void SetString(char * ptr); const char * GetString();... };

Other Binary Operators int main(){ String str1("Test"); String str2; str2.SetString("Ping"); return 0; }

Other Binary Operators ► What if we want to change the string from “Ping” to “Pong”?? {ONLY 1 character to be changed…} ► Possible solution:  Call: str2.SetString("Pong");  This will delete the current buffer and allocate a new one  Too much overhead if string is too big

Other Binary Operators ► Or, we can add a function which changes a character at nth location class String{... public: void SetChar(char c, int pos);... };

Other Binary Operators void SetChar(char c, int pos){ if (bufferPtr != NULL){ if (pos>0 && pos <= size) bufferPtr[pos] = c; } }

Other Binary Operators ► Now we can efficiently change a single character: String str1("Ping"); str1.SetChar('o', 2); // str1 is now changed to “ Pong ”

Subscript Operator ► An elegant solution: ► Overloading the subscript “ [] ” operator

Subscript Operator int main(){ String str2; str2.SetString("Ping"); str[2] = 'o'; cout << str[2]; return 0; }

Subscript Operator class String{... public: char & operator[](int);... };

Subscript Operator char & String::operator[](int pos){ assert(pos>0 && pos <= size); return stringPtr[pos - 1]; }

Subscript Operator int main() { String s1("Ping"); cout << str.GetString() << endl; s1[2] = 'o'; cout << str.GetString(); return 0; }

Subscript Operator ► Output: Ping Pong

Overloading () ► Must be a member function ► Any number of parameters can be specified ► Any return type can be specified ► Operator() can perform any generic operation

Function Operator class String{... public: char & operator()(int);... };

Function Operator char & String::operator()(int pos){ assert(pos>0 && pos <= size); return bufferPtr[pos - 1]; }

Subscript Operator int main(){ String s1("Ping"); char g = s1(2); // g = ‘i’ s1(2) = 'o'; cout << g << "\n"; cout << str.GetString(); return 0; }

Function Operator ► Output: i Pong

Function Operator class String{... public: String operator()(int, int);... };

Function Operator String String::operator()(int index, int subLength){ assert(index>0 && index + subLength - 1 <= size); char * ptr = new char[subLength + 1]; for (int i = 0; i < subLength; ++i) ptr[i] = bufferPtr[i + index - 1]; ptr[subLength] = ‘\0’; String str(ptr); delete[] ptr; return str; }

Function Operator int main(){ String s(“Hello World”); // “<<“ is overloaded cout << s(1, 5); return 0; }

Function Operator Output: Hello

Unary Operators ► Unary operators:  & * ! ~ ► Examples: --x -(x++) !(*ptr ++)

Unary Operators ► Unary operators are usually prefix, except for ++ and -- ► ++ and -- both act as prefix and postfix ► Example: h++; g h - --i;

Unary Operators ► General syntax for unary operators: Member Functions: TYPE & operator OP (); Non-member Functions: Friend TYPE & operator OP (TYPE & t);

Unary Operators ► Overloading unary ‘-’: class Complex{... Complex operator - (); // friend Complex operator -(Complex &); };

Unary Operators ► Member function definition: Complex Complex::operator -(){ Complex temp; temp.real = -real; temp.img = -img; return temp; }

Unary Operators Complex c1(1.0, 2.0), c2; c2 = -c1; // c2.real = -1.0 // c2.img = -2.0 Unary ‘+’ is overloaded in the same way