Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and Information Science,

Slides:



Advertisements
Similar presentations
Chapter 11 Operator Overloading; String and Array Objects Chapter 11 Operator Overloading; String and Array Objects Part I.
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.
Operator Overloading Fundamentals
Operator Overloading. Basics Define operations on user-defined data types –Perform same operation as it is supposed to but, with operands of the user-defined.
Chapter 14: Overloading and Templates C++ Programming: Program Design Including Data Structures, Fifth Edition.
Rossella Lau Lecture 10, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 10: Operator overload  Operator overload.
 2006 Pearson Education, Inc. All rights reserved Operator Overloading.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 18 - C++ Operator Overloading Outline 18.1Introduction.
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 18 - Operator Overloading Outline 18.1Introduction 18.2Fundamentals of Operator Overloading 18.3Restrictions.
 2006 Pearson Education, Inc. All rights reserved Operator Overloading; String and Array Objects.
Chapter 15: Operator Overloading
 2008 Pearson Education, Inc. All rights reserved Operator Overloading; String and Array Objects.
Operator OverloadingCS-2303, C-Term Operator Overloading CS-2303 System Programming Concepts (Slides include materials from The C Programming Language,
Operator overloading Object Oriented Programming.
Operator Overloading in C++
Review of C++ Programming Part II Sheng-Fang Huang.
Chapter 18 - Operator Overloading Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
More About Classes Chapter Instance And Static Members instance variable: a member variable in a class. Each object has its own copy. static variable:
Operator Overloading and Type Conversions
Operatorsand Operators Overloading. Introduction C++ allows operators to be overloaded specifically for a user-defined class. Operator overloading offers.
 2006 Pearson Education, Inc. All rights reserved Operator Overloading; String and Array Objects.
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.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Part 9:
Operator overloading and type convesions BCAS,Bapatla B.mohini devi.
C++ Class Members Class Definition – class Name – { – public: » constructor(s) » destructor » function members » data members – protected: » function members.
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 Operator Overloading allows a programmer to define new types from the built-in types. –Operator Overloading is useful for redefining.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
 2008 Pearson Education, Inc. All rights reserved Operator Overloading.
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Operator Overloading.
CS Object Oriented Programming Using C++
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 25 December 1, 2009.
1 Chapter 8 - Operator Overloading Outline 8.1Introduction 8.2Fundamentals of Operator Overloading 8.3Restrictions on Operator Overloading 8.4Operator.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14: More About Classes.
1 Advanced Topics in Functions Lecture Unitary Scope Resolution Operator Unary scope resolution operator ( :: )  Access global variable if.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 8 - Operator Overloading Outline 8.1Introduction 8.2Fundamentals of Operator Overloading.
Learning Objectives Fundamentals of Operator Overloading. Restrictions of Operator Overloading. Global and member Operator. Overloading Stream-Insertion.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 26 Clicker Questions December 3, 2009.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 8 - Operator Overloading Outline 8.1Introduction 8.2Fundamentals of Operator Overloading 8.3Restrictions.
1 CSC241: Object Oriented Programming Lecture No 08.
Dale Roberts 1 Operator Overloading Member Functions Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer.
 2008 Pearson Education, Inc. All rights reserved Operator Overloading; String and Array Objects.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Review slides Mar 15, 2005.
Operator Overloading What is operator overloading? Most predefined operators (arithmetic, logic, etc.) in C++ can be overloaded when applied to objects.
 2006 Pearson Education, Inc. All rights reserved Operator Overloading; String and Array Objects.
Operator Overloading.
Chapter 18 - C++ Operator Overloading
CSE1002 – Problem Solving with Object Oriented Programming
IS Program Design and Software Tools Introduction to C++ Programming
Department of Computer and Information Science, School of Science, IUPUI Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI
Operator Overloading; String and Array Objects
Polymorphism in C++ Operator Overloading
Operator Overloading; String and Array Objects
Operator Overloading.
Operator Overloading; String and Array Objects
Chapter 8 - Operator Overloading
Operator Overloading.
Operator Overloading; String and Array Objects
Operator Overloading Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
COP 3330 Object-oriented Programming in C++
Recitation Course 0603 Speaker: Liu Yu-Jiun.
Operator Overloading; String and Array Objects
Chapter 18 - Operator Overloading
Operator Overloading; String and Array Objects
Presentation transcript:

Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and Information Science, School of Science, IUPUI Fall 2003

Dale Roberts Operator Overloading Function-call notation is cumbersome for certain kinds of classes, especially mathematical classes Allows extendable design Most appropriate for math classes. eg. Matrix, Vector, etc. Gives Operators Class-Specific Functionality In-built or Standard Overloading for Basic Numerical Data Types -- + can be used with int, float, doubles Analogous to Function Overloading -- is Used as the Function Name 40 Operators can be Overloaded to Give Class-Specific Functionality C++ enables programmers to overload operators to be sensitive to the context in which they are used. The compiler generates appropriate code Easier to read

Dale Roberts Requirements of Overloaded Operators Their Meaning Should be Intuitive -- + Should Mean Addition When Appropriate, they Should be Associative -- a + b Should Result in an Object, c of the Same Class If these Conditions are Not Satisfied then it is Better to Use Member Functions and Not Operator Overloading To use an operator on class objects, that operator must be overloaded - with two exceptions - the assignment operator (=), which performs a member wise copy, and the address (&) operator

Dale Roberts Forms of Overloaded Operators Member Functions Friend Functions Free-Standing or Global Functions

Dale Roberts Operator Functions When to make class members, friends or global functions? If member function, then this is implicitly available for one of the arguments When overloading ( ), [ ], ->, or =, the operator overloading function must be declared as a class member. For other operators, the overloading functions can be non- members When an operator function is implemented as a member function, the left most (or only in the case of unary operators) operand must be a class object (or a reference to a class object) of operator's class If the left operand must be an object of a different class or a built-in type, this operator must be implemented as a non-class member. eg. > operators An operator function implemented as a non-member must be a friend if it needs to access non-public data members of that class. The overloaded << operator must have a left operand of type ostream. Therefore, it must be a non-member function. Also, it may require access to the private data members of the class. Thus, it needs to be a friend function for that class. Similar observation holds for >> operator which has a left operand of type istream. Operator member functions are classed only when the left operand of a binary operator is specifically an object of that class or when the single operand of a unary operator is an object of that class. If the operator needs to be commutative (a + b = b + a), then making it a non-member function is necessary.

Dale Roberts Restrictions of Overloaded Operators New Operators CANNOT be Created Fundamental Data Types (e.g. int) CANNOT be Overloaded Operator Priority CANNOT be Changed Operator Associativity CANNOT be Changed The arity of CANNOT be changed -- + can Take ONLY One or TWO Arguments Two Separate Overloaded Functions (With Different Signatures) can be Created for Operators Which Exist in Pre-fix and Post-fix Form Overloaded Operators are NOT IMPLICITLY Associative or Commutative, Even if the Original Operators were Associative or Commutative -- Associativity and Commutativity MUST be EXPLICITLY IMPLEMENTED Overloading the operator + does not automatically overload related operators (+=, ++, etc). If needed, these related operators must be explicitly overloaded

Dale Roberts Unary Overloaded Operators -- Member Functions Invocation in Two Ways -- (Direct) or (As a Function) class number{ class number{ int n; int n; public: public: number(int x = 0):n(x){}; number(int x = 0):n(x){}; number operator-(){return number (-n);} number operator-(){return number (-n);} }; }; main() main() { number a(1), b(2), c, d; number a(1), b(2), c, d; //Invocation of "-" Operator -- direct //Invocation of "-" Operator -- direct d = -b; //d.n = -2 d = -b; //d.n = -2 //Invocation of "-" Operator -- Function //Invocation of "-" Operator -- Function c = a.operator-(); //c.n = -1 c = a.operator-(); //c.n = -1 }

Dale Roberts Binary Overloaded Operators -- Member Functions Invocation in Two Ways -- ObjectB (direct) or (As a Function) class number{ class number{ int n; int n; public: public: number(int x = 0):n(x){}; number(int x = 0):n(x){}; number operator+(number ip) number operator+(number ip) {return number (ip.n + n);} {return number (ip.n + n);} }; }; main() main() { number a(1), b(2), c, d; number a(1), b(2), c, d; //Invocation of "+" Operator -- direct //Invocation of "+" Operator -- direct d = a + b; //d.n = 3 d = a + b; //d.n = 3 //Invocation of "+" Operator -- Function //Invocation of "+" Operator -- Function c = d.operator+(b); //c.n = d.n + b.n = 5 c = d.operator+(b); //c.n = d.n + b.n = 5 }

Dale Roberts Operator Overloading Using a Friend Function Number of Parameters Accepted by an Overloaded Friend Operator Function Depend Upon the Operator Type -- One for Unary Operators and Two for Binary Operators class complex{ class complex{ int re, im; int re, im; public: public: complex(int ip1 = 0, int ip2 = 0) complex(int ip1 = 0, int ip2 = 0) :re(ip1), im(ip2){} :re(ip1), im(ip2){} friend complex operator+(complex, complex); friend complex operator+(complex, complex); }; }; //Friend Operator + Function //Friend Operator + Function complex operator+(complex a, complex b) complex operator+(complex a, complex b) {return complex(a.re+b.re, a.im+b.im);} {return complex(a.re+b.re, a.im+b.im);} main(){ main(){ complex one(1,1), two(2,2), three; complex one(1,1), two(2,2), three; three = operator+(one, two); //three = one + two three = operator+(one, two); //three = one + two }

Dale Roberts Operator Functions as Class Members vs. as friend Functions Non-member overloaded operator functions Enable the operator to be commutative HugeInteger bigInteger; int integer; int integer; bigInteger = integer + bigInteger; bigInteger = integer + bigInteger;or bigInteger = biginteger + integer; bigInteger = biginteger + integer;

Dale Roberts Global Operator Overloading Similar to friend Function Overloading, Except the Keyword friend is Omitted and Global Functions CANNOT ACCESS private Members class complex{ //All Public Members! class complex{ //All Public Members! public: public: int re, im; int re, im; complex(int ip1 = 0, int ip2 = 0) complex(int ip1 = 0, int ip2 = 0) :re(ip1), im(ip2){} :re(ip1), im(ip2){} }; }; void operator!(complex a) void operator!(complex a) { int temp = a.re; a.re = a.im; a.im = temp; int temp = a.re; a.re = a.im; a.im = temp; cout << "Real: " << a.re << endl; cout << "Real: " << a.re << endl; cout << "Imaginary: " << a.im << endl; cout << "Imaginary: " << a.im << endl; } main() main() { complex one(1,2); complex one(1,2); operator!(one); operator!(one); }

Dale Roberts Overloading of Operators Having a Variable Arity Operators Such as + and - Can be Unary or Binary Overloading of Such Operators Involves Creating a Unary Function (One Operand) and a Binary Function (Two Operands) Only if Both the Forms are Used, They Need to be Implemented class number{ class number{ int n; int n; public: public: number(int x = 0):n(x){} number(int x = 0):n(x){} number operator-(){n = -n; return *this;} number operator-(){n = -n; return *this;} number operator-(number ip) {return(n-ip.n);} number operator-(number ip) {return(n-ip.n);} }; }; main(){ main(){ number one(1), two(2), three; number one(1), two(2), three; one = -one; //unary operator one = -one; //unary operator three = one - two; //three.n = -3 three = one - two; //three.n = -3 }

Dale Roberts Operators with Prefix and Postfix Forms Separate Functions for Each -- Prefix and Postfix -- Forms are Needed Prefix Form is Treated as an Unary Operator Postfix Form is Treated as a Binary Operator

Dale Roberts Prefix Overloaded Function -- Example class number{ class number{ int n; int n; public: public: number(int x):n(x){}; //Constructor number(int x):n(x){}; //Constructor //prefix operator -- unary //prefix operator -- unary number operator++(); number operator++();}; number number::operator++(){ number number::operator++(){ n++; return *this;} n++; return *this;} main(){ main(){ number one(10); //one.n = 10 number one(10); //one.n = 10 one++; //one.n = 11 one++; //one.n = 11 }

Dale Roberts Postfix Overloaded Function -- Example Postfix Operator is Implemented as a Binary Operator with an int Argument with a Default Value of 0 class number{ class number{ int n; int n; public: public: number(int x):n(x){}; //Constructor number(int x):n(x){}; //Constructor //postfix operator -- binary -- int argument //postfix operator -- binary -- int argument number operator++(int); number operator++(int); }; }; number number::operator++(int y) number number::operator++(int y) {n += y; return *this;} {n += y; return *this;} main() main() { number one(10); //one.n = 10 number one(10); //one.n = 10 one.operator++(2); //one.n = 12 one.operator++(2); //one.n = 12 }

Dale Roberts Special Overloading Forms A Few Operators Require Special Treatments During Overloading Conversion Operator const Array Operator Function Call -- Parenthesis Operator Stream Insertion -- << Operator Stream Extraction -- >> Operator Pointer to Member -- -> Operator Assignment Operator new Operator delete Operator

Dale Roberts Overloading Stream-Insertion and Stream-Extraction Operators Overloaded > operators Must have left operand of types ostream &, istream & respectively It must be a non-member function (left operand not an object of the class) It must be a friend function if it accesses private data members

Dale Roberts 1// Fig. 18.3: fig18_03.cpp 2// Overloading the stream-insertion and 3// stream-extraction operators. 4#include 5 6using std::cout; 7using std::cin; 8using std::endl; 9using std::ostream; 10using std::istream; 11 12#include 13 14using std::setw; 15 16class PhoneNumber { 17 friend ostream &operator<<( ostream&, const PhoneNumber & ); 18 friend istream &operator>>( istream&, PhoneNumber & ); 19 20private: 21 char areaCode[ 4 ]; // 3-digit area code and null 22 char exchange[ 4 ]; // 3-digit exchange and null 23 char line[ 5 ]; // 4-digit line and null 24}; 25 26// Overloaded stream-insertion operator (cannot be 27// a member function if we would like to invoke it with 28// cout << somePhoneNumber;). 29ostream &operator<<( ostream &output, const PhoneNumber &num ) 30{

Dale Roberts 31 output << "(" << num.areaCode << ") " 32 << num.exchange << "-" << num.line; 33 return output; // enables cout << a << b << c; 34} 35 36istream &operator>>( istream &input, PhoneNumber &num ) 37{ 38 input.ignore(); // skip ( 39 input >> setw( 4 ) >> num.areaCode; // input area code 40 input.ignore( 2 ); // skip ) and space 41 input >> setw( 4 ) >> num.exchange; // input exchange 42 input.ignore(); // skip dash (-) 43 input >> setw( 5 ) >> num.line; // input line 44 return input; // enables cin >> a >> b >> c; 45} 46 47int main() 48{ 49 PhoneNumber phone; // create object phone cout << "Enter phone number in the form (123) :\n"; // cin >> phone invokes operator>> function by 54 // issuing the call operator>>( cin, phone ). 55 cin >> phone; // cout << phone invokes operator<< function by 58 // issuing the call operator<<( cout, phone ). 59 cout << "The phone number entered was: " << phone << endl; 60 return 0; 61}

Dale Roberts Enter phone number in the form (123) : (800) The phone number entered was: (800)

Dale Roberts Converting between Types Cast operator Convert objects into built-in types or other objects Conversion operator must be a non- static member function. Cannot be a friend function Do not specify return type For user-defined class A A::operator char *() const; // A to char A::operator int() const; //A to int A::operator otherClass() const; //A to otherClass When compiler sees (char *) s it calls s.operator char*()

Dale Roberts Converting between Types (cont) The compiler can call these functions to create temporary objects. If s is not of type char * Calls A::operator char *() const; for cout << s; cout << s;

Dale Roberts Special overloading forms - Example Special Forms Example Special Forms Example

Dale Roberts Acknowledgements These slides were originally development by Dr. Uday Murthy and Dr. Rajeev Raje. Some contents comes from the Deitel slides that accompany your text.