24
Dale Roberts Operator Overloading Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI E-mail: [email protected] Department of Computer and Information Science, School of Science, IUPUI Fall 2003

Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer…

Embed Size (px)

DESCRIPTION

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

Citation preview

Page 1: Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer…

Dale Roberts

Operator OverloadingOperator Overloading

Dale Roberts, LecturerComputer Science, IUPUIE-mail: [email protected]

Department of Computer and Information Science,School of Science, IUPUI

Fall 2003

Page 2: Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer…

Dale Roberts

Operator Overloading Operator Overloading FFunction-call notation is cumbersome for certain kinds of classes, especially unction-call notation is cumbersome for certain kinds of classes, especially mathematical classesmathematical classes Allows extendable design Allows extendable design Most appropriate for math classes. eg. Matrix, Vector, etc. Most appropriate for math classes. eg. Matrix, Vector, etc. Gives Operators Class-Specific Functionality Gives Operators Class-Specific Functionality In-built or Standard Overloading for Basic Numerical Data Types -- In-built or Standard Overloading for Basic Numerical Data Types -- ++ can be used can be used with with int, float, doublesint, float, doubles Analogous to Function Overloading -- Analogous to Function Overloading -- operator@operator@ is Used as the Function Name is Used as the Function Name 40 Operators can be Overloaded to Give Class-Specific Functionality 40 Operators can be Overloaded to Give Class-Specific Functionality

C++ enables programmers to overload operators to be sensitive to the context in C++ enables programmers to overload operators to be sensitive to the context in which they are used.  The compiler generates appropriate code which they are used.  The compiler generates appropriate code Easier to read Easier to read

Operators that can be overloaded

+ - * / % ^ & | ~ ! = < > += -= *= /= %= ^= &= |= << >> >>= <<= == != <= >= && || ++ -- ->* , -> [] () new delete new[] delete[]

Page 3: Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer…

Dale Roberts

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

Page 4: Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer…

Dale Roberts

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

Page 5: Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer…

Dale Roberts

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

Page 6: Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer…

Dale Roberts

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

Page 7: Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer…

Dale Roberts

Unary Overloaded Operators -- Member FunctionsUnary Overloaded Operators -- Member Functions Invocation in Two Ways -- Invocation in Two Ways -- Object@Object@ (Direct) or (Direct) or Object.operator@()Object.operator@() (As a Function) (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 = -2d = -b; //d.n = -2 //Invocation of "-" Operator -- Function//Invocation of "-" Operator -- Function c = a.operator-(); //c.n = -1c = a.operator-(); //c.n = -1 }}

Page 8: Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer…

Dale Roberts

Binary Overloaded Operators -- Member FunctionsBinary Overloaded Operators -- Member Functions Invocation in Two Ways -- Invocation in Two Ways -- ObjectA @ ObjectBObjectA @ ObjectB (direct) or (direct) or ObjectA.operator@(ObjectB)ObjectA.operator@(ObjectB) (As a Function) (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 = 3d = a + b; //d.n = 3 //Invocation of "+" Operator -- Function//Invocation of "+" Operator -- Function c = d.operator+(b); //c.n = d.n + b.n = 5c = d.operator+(b); //c.n = d.n + b.n = 5 }}

Page 9: Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer…

Dale Roberts

Operator Overloading Using a Friend FunctionOperator Overloading Using a Friend FunctionNumber of Parameters Accepted by an Overloaded Friend Operator Number of Parameters Accepted by an Overloaded Friend Operator Function Depend Upon the Operator Type -- One for Unary Operators and Function Depend Upon the Operator Type -- One for Unary Operators and Two for Binary Operators 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 + twothree = operator+(one, two); //three = one + two }}

Page 10: Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer…

Dale Roberts

Operator Functions as Class Members vs. as Operator Functions as Class Members vs. as friendfriend Functions Functions

Non-member overloaded operator functionsNon-member overloaded operator functionsEnable the operator to be commutativeEnable the operator to be commutative

HugeInteger bigInteger; HugeInteger bigInteger; int integer;int integer; bigInteger = integer + bigInteger;bigInteger = integer + bigInteger;

oror

bigInteger = biginteger + integer;bigInteger = biginteger + integer;

Page 11: Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer…

Dale Roberts

Global Operator OverloadingGlobal Operator OverloadingSimilar to Similar to friendfriend Function Overloading, Except the Keyword Function Overloading, Except the Keyword friendfriend is Omitted and is Omitted and Global Functions CANNOT ACCESS Global Functions CANNOT ACCESS privateprivate Members 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); }}

Page 12: Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer…

Dale Roberts

Overloading of Operators Having a Variable ArityOverloading of Operators Having a Variable Arity Operators Such as Operators Such as ++ and and -- Can be Unary or Binary Can be Unary or Binary Overloading of Such Operators Involves Creating a Unary Function Overloading of Such Operators Involves Creating a Unary Function (One Operand) and a Binary Function (Two Operands) (One Operand) and a Binary Function (Two Operands) Only if Both the Forms are Used, They Need to be Implemented 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 operatorone = -one; //unary operator three = one - two; //three.n = -3three = one - two; //three.n = -3 }}

Page 13: Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer…

Dale Roberts

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

Page 14: Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer…

Dale Roberts

Prefix Overloaded Function -- Example Prefix Overloaded Function -- Example class number{class number{ int n;int n; public:public: number(int x):n(x){}; //Constructornumber(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 = 10number one(10); //one.n = 10 one++; //one.n = 11one++; //one.n = 11 }}

Page 15: Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer…

Dale Roberts

Postfix Overloaded Function -- Example Postfix Overloaded Function -- Example Postfix Operator is Implemented as a Binary Operator with an Postfix Operator is Implemented as a Binary Operator with an intint Argument with a Default Value of 0 Argument with a Default Value of 0

class number{class number{ int n;int n; public:public: number(int x):n(x){}; //Constructornumber(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 = 10number one(10); //one.n = 10 one.operator++(2); //one.n = 12one.operator++(2); //one.n = 12 }}

Page 16: Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer…

Dale Roberts

Special Overloading Forms Special Overloading Forms A Few Operators Require Special Treatments A Few Operators Require Special Treatments During Overloading During Overloading Conversion Operator Conversion Operator constconst Array Operator Array Operator Function Call -- Parenthesis Operator Function Call -- Parenthesis Operator Stream Insertion -- Stream Insertion -- <<<< Operator Operator Stream Extraction -- Stream Extraction -- >>>> Operator Operator Pointer to Member -- Pointer to Member -- ->-> Operator Operator Assignment Operator Assignment Operator newnew Operator Operator deletedelete Operator Operator

Page 17: Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer…

Dale Roberts

Overloading Stream-Insertion and Stream-Extraction OperatorsOverloading Stream-Insertion and Stream-Extraction Operators

Overloaded Overloaded << << andand >> >> operators operators Must have left operand of types Must have left operand of types ostreamostream &&, , istreamistream && respectivelyrespectivelyIt must be a non-member function (left operand not an It must be a non-member function (left operand not an object of the class)object of the class)It must be a It must be a friendfriend function if it accesses private data function if it accesses private data membersmembers

Page 18: Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer…

Dale Roberts

1 // Fig. 18.3: fig18_03.cpp2 // Overloading the stream-insertion and 3 // stream-extraction operators.4 #include <iostream>56 using std::cout;7 using std::cin;8 using std::endl;9 using std::ostream;10 using std::istream;1112 #include <iomanip>1314 using std::setw;1516 class PhoneNumber {17 friend ostream &operator<<( ostream&, const PhoneNumber & );18 friend istream &operator>>( istream&, PhoneNumber & );1920 private:21 char areaCode[ 4 ]; // 3-digit area code and null22 char exchange[ 4 ]; // 3-digit exchange and null23 char line[ 5 ]; // 4-digit line and null24 };2526 // Overloaded stream-insertion operator (cannot be 27 // a member function if we would like to invoke it with28 // cout << somePhoneNumber;).29 ostream &operator<<( ostream &output, const PhoneNumber &num )30 {

Page 19: Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer…

Dale Roberts

31 output << "(" << num.areaCode << ") "32 << num.exchange << "-" << num.line;33 return output; // enables cout << a << b << c;34 }3536 istream &operator>>( istream &input, PhoneNumber &num )37 {38 input.ignore(); // skip (39 input >> setw( 4 ) >> num.areaCode; // input area code40 input.ignore( 2 ); // skip ) and space41 input >> setw( 4 ) >> num.exchange; // input exchange42 input.ignore(); // skip dash (-)43 input >> setw( 5 ) >> num.line; // input line44 return input; // enables cin >> a >> b >> c;45 }4647 int main()48 {49 PhoneNumber phone; // create object phone5051 cout << "Enter phone number in the form (123) 456-7890:\n";5253 // cin >> phone invokes operator>> function by 54 // issuing the call operator>>( cin, phone ).55 cin >> phone;5657 // cout << phone invokes operator<< function by58 // issuing the call operator<<( cout, phone ). 59 cout << "The phone number entered was: " << phone << endl;60 return 0;61 }

Page 20: Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer…

Dale Roberts

Enter phone number in the form (123) 456-7890:(800) 555-1212The phone number entered was: (800) 555-1212

Page 21: Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer…

Dale Roberts

Converting between TypesConverting between TypesCast operatorCast operator

Convert objects into built-in types or other objects Convert objects into built-in types or other objects Conversion operator must be a non-Conversion operator must be a non-staticstatic member member function.function.Cannot be a Cannot be a friendfriend function functionDo not specify return typeDo not specify return type

For user-defined class For user-defined class AAA::operator char *() const; // A to charA::operator char *() const; // A to charA::operator int() const; //A to intA::operator int() const; //A to intA::operator otherClass() const; //A to otherClassA::operator otherClass() const; //A to otherClass

When compiler sees When compiler sees (char *) s(char *) s it calls it calls s.operator char*()s.operator char*()

Page 22: Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer…

Dale Roberts

Converting between Types (cont)Converting between Types (cont)

The compiler can call these functions to create The compiler can call these functions to create temporary objects.temporary objects.

If If ss is not of type is not of type char *char *

Calls Calls A::operator char *() const; A::operator char *() const; for for cout << s;cout << s;

Page 23: Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer…

Dale Roberts

Special overloading forms - Example Special overloading forms - Example Special Forms ExampleSpecial Forms Example

Page 24: Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer…

Dale Roberts

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