Overloading · Overloading Operators— The Rules Associativity refers to the order in which...

33
1 Operator Overloading Operator Overloading Friend Functions & Forms Friend Functions & Forms CSC 330 Object Oriented Programming

Transcript of Overloading · Overloading Operators— The Rules Associativity refers to the order in which...

Page 1: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

1

Operator OverloadingOperator OverloadingFriend Functions & FormsFriend Functions & Forms

CSC 330 Object Oriented Programming

Page 2: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

2

Most of C++’s operators can be overloadedMost of C++’s operators can be overloaded

.. Operators that can be overloaded

+ - * / % ^ & |

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

Restrictions on Operator OverloadingRestrictions on Operator Overloading

No new operators can be createdUse only existing operators

Page 3: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

3

Arithmetic OperatorsArithmetic Operators

Page 4: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

4

Comparison OperatorsComparison Operators

Page 5: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

5

Logical OperatorsLogical Operators

Page 6: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

6

Bitwise OperatorBitwise Operator

Page 7: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

7

Other OperatorsOther Operators

Page 8: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

8

Examples of Bitwise OperatorsExamples of Bitwise Operators

Page 9: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

9

Restrictions on Operator OverloadingRestrictions on Operator Overloading cont’dcont’d

Arity (number of operands) cannot be changedArity (number of operands) cannot be changedUnary operators remain unary, and binary operators remain Unary operators remain unary, and binary operators remain binarybinaryOperators Operators &&, , **, , ++ and and -- each have unary and binary each have unary and binary versionsversions

Unary and binary versions can be overloaded separatelyUnary and binary versions can be overloaded separately

Page 10: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

10

Overloading OperatorsOverloading Operators——The RulesThe Rules

Associativity Associativity refers to refers to the order in which the order in which actions within an actions within an expression are carried expression are carried outoutYou cannot change You cannot change associativity when you associativity when you overload operatorsoverload operatorsYou also cannot change You also cannot change the normal precedence the normal precedence of any operatorof any operator

Page 11: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

11

Overloading OperatorsOverloading Operators——The RulesThe Rules

Page 12: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

12

A A ComplexComplex ClassClass

#include <iostream>

class Complex{

double real;double image;

public:Complex(double re=0, double im=0){

this->real = re;this->image = im;

}Complex add(const Complex& c) const{

Complex result;result.real = this->real + c.real;result.image = this->image + c.image;return result;

}....

};

Page 13: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

13

Using the Using the ComplexComplex ClassClass

int main(){

Complex z(1,2), w(3,4);Complex a = z.add(w); // want a = z+wa.display();

}

(4,6)

Page 14: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

14

Operator FunctionsOperator Functions

operatoroperator keyword together with an operatorkeyword together with an operatoroperator+operator+

operatoroperator--

etc.etc.

Can overload all operators except:Can overload all operators except:::::..**

?:?:

Page 15: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

15

ComplexComplex with with operator+operator+

class Complex{

// ...public:

// ...Complex operator+(const Complex& c) const{

Complex result;result.real = this->real + c.real;result.image = this->image + c.image;return result;

}// ...

};

int main(){

Complex z(1,2), w(3,4);Complex a = z + w; // z.operator+(w)a.display();

}

Page 16: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

16

Global Global ComplexComplex OperatorsOperators

class Complex{

double real, image;public:

Complex(double x = 0, double y = 0){

this->real = x;this->imag = y;

}double getReal() const {return real;}double getImage() const {return image;}// ...

};

Complex operator+(const Complex& c1, const Complex& c2){

double re = c1.getReal() + c2.getReal();double im = c1.getImage() + c2.getImage();Complex result(re, im);return result;

}

Page 17: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

17

friendfriend FunctionsFunctions

class Complex {class Complex {public:public:

Complex( );Complex( ); // default// defaultComplex( double ) ; // real givenComplex( double ) ; // real givenComplex( double, double ) ; // both givenComplex( double, double ) ; // both givenvoid write( ) const; void write( ) const; // friend functions // friend functions friend Complex operator+( const Complex&, const Complex& ) ; friend Complex operator+( const Complex&, const Complex& ) ; friend Complex operatorfriend Complex operator--( const Complex&, const Complex& ) ;( const Complex&, const Complex& ) ;friend Complex operator*( const Complex&, const Complex& ) ;friend Complex operator*( const Complex&, const Complex& ) ;friend Complex operator/( const Complex&, const Complex& ) ;friend Complex operator/( const Complex&, const Complex& ) ;

private: private: double real; double real; double image;double image;

} ;} ;

Page 18: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

18

Implementation FileImplementation File

// Complex + as top// Complex + as top--level friendlevel friendComplex operator+( const Complex& t, const Complex& u ) {Complex operator+( const Complex& t, const Complex& u ) {

return Complex( return Complex( t.realt.real + + u.realu.real, , t.imaget.image + + u.imageu.image ) ;) ;}}// Complex // Complex -- as topas top--level friendlevel friendComplex operatorComplex operator--( const Complex& t, const Complex& u ) { ( const Complex& t, const Complex& u ) {

return Complex( return Complex( t.realt.real -- u.realu.real, , t.imaget.image -- u.imageu.image ) ;) ;}}// Complex * as top// Complex * as top--level friendlevel friendComplex operator*( const Complex& t, const Complex& u ) {Complex operator*( const Complex& t, const Complex& u ) {

return Complex( return Complex( t.realt.real * * u.realu.real -- t.imagt.imag * * u.imageu.image,,t.imagt.imag * * u.realu.real + + t.realt.real * * u.imageu.image ) ;) ;

}}// Complex / as top// Complex / as top--level friendlevel friendComplex operator/( const Complex& t, const Complex& u ) {Complex operator/( const Complex& t, const Complex& u ) {

double double abs_sqabs_sq = = u.realu.real * * u.realu.real + + u.imageu.image * * u.imageu.image; ; return Complex( (return Complex( (t.realt.real * * u.realu.real + + t.imaget.image * * u.image)/abs_squ.image)/abs_sq,,

((t.imaget.image * * u.realu.real -- tt--real * real * u.image)/abs_squ.image)/abs_sq););}}

Page 19: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

19

DiscussionsDiscussions

Friendship (i.e., using the friend keyword) is a complex and danFriendship (i.e., using the friend keyword) is a complex and dangerous topic for gerous topic for various reasons: various reasons:

Friendship, when applied to program design, is an Friendship, when applied to program design, is an escape mechanismescape mechanism allowing us to allowing us to circumvent the principles of encapsulation and data hiding. The circumvent the principles of encapsulation and data hiding. The use of friends use of friends should therefore be should therefore be minimizedminimized to situations where they can be used naturally. to situations where they can be used naturally.

If friends are used, realize that friend functions or classes beIf friends are used, realize that friend functions or classes become implementation come implementation dependent on the classes declaring them as friends. Once the intdependent on the classes declaring them as friends. Once the internal organization ernal organization of the data of a class declaring friends changes, all its friendof the data of a class declaring friends changes, all its friends must be recompiled s must be recompiled (and possibly modified) as well. (and possibly modified) as well.

Therefore, as a rule of thumb: Therefore, as a rule of thumb: don'tdon't use friend functions or classes. use friend functions or classes.

Page 20: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

20

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 real, image;int real, image;Complex(intComplex(int ip1 = 0, int ip2 = 0)ip1 = 0, int ip2 = 0)

:real(ip1), image(ip2){};:real(ip1), image(ip2){};};};void void operator!(Complexoperator!(Complex a)a){ {

int temp = int temp = a.reala.real; ; a.reala.real = = a.imagea.image; ; a.imagea.image = temp;= temp;coutcout << "Real: " << << "Real: " << a.reala.real << << endlendl;;coutcout << "Imaginary: " << << "Imaginary: " << a.imagea.image << << endlendl;;

}}

main()main(){{

Complex one(1,2);Complex one(1,2);!one;!one;

}}

Page 21: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

21

Overloading of Operators Having a Variable Overloading of Operators Having a Variable ArityArityOperators Such as Operators Such as -- Can be Unary or Binary Can be Unary or Binary Overloading of Such Operators Involves Creating a Unary FunctionOverloading of Such Operators Involves Creating a Unary Function (One (One Operand) and a Binary Function (Two Operands) Operand) and a Binary Function (Two Operands) Only if Both Forms are Used, They Need to be Implemented Only if Both Forms are Used, They Need to be Implemented

class Number{class Number{int n;int n;

public:public:Number(intNumber(int x = 0):n(x){}x = 0):n(x){}Number operatorNumber operator--(){n = (){n = --n; return *this;}n; return *this;}Number operatorNumber operator--(Number ip) (Number ip) {n = n {n = n –– ip.nip.n; return *this;}; return *this;}

};};main(){main(){

Number one(1), two(2), three;Number one(1), two(2), three;one = one = --one; //unary operatorone; //unary operatorthree = one three = one -- two; //two; //three.nthree.n = = --33

}}

Page 22: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

22

Operators with Prefix and Postfix Forms Operators with Prefix and Postfix Forms Separate Functions for Each Separate Functions for Each ---- Prefix and Prefix and Postfix Postfix ---- Forms are Needed 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 23: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

23

Prefix Overloaded Function Prefix Overloaded Function ---- Example Example class Number{class Number{

int n;int n;public:public:Number(intNumber(int x):n(xx):n(x){}; //Constructor){}; //Constructor//prefix operator //prefix operator ---- unaryunaryNumber operator++(); Number operator++();

};};Number Number Number::operatorNumber::operator++(){++(){

n++; return *this;}n++; return *this;}main(){main(){

Number one(10); //Number one(10); //one.none.n = 10= 10++one; //++one; //one.none.n = 11= 11

}}

Page 24: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

24

Postfix Overloaded Function Postfix Overloaded Function ---- Example Example Postfix Operator is Implemented as a Binary Operator with an Postfix Operator is Implemented as a Binary Operator with an intintArgument with a Default Value of 0 . When specifying an Argument with a Default Value of 0 . When specifying an overloaded operator for the postfix form of the increment or overloaded operator for the postfix form of the increment or decrement operator, the additional argument must be of type int;decrement operator, the additional argument must be of type int;specifying any other type generates an error. specifying any other type generates an error. class Number{class Number{

int n;int n;public:public:

Number(intNumber(int x):n(xx):n(x){}; //Constructor){}; //Constructor//postfix operator //postfix operator ---- binary binary ---- int argumentint argumentNumber Number operator++(intoperator++(int); );

};};Number Number Number::operator++(intNumber::operator++(int y)y)

{if (y != 0) n += y; else n++; return *this;}{if (y != 0) n += y; else n++; return *this;}

Page 25: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

25

Postfix overloaded functionPostfix overloaded function——Example (Cont)Example (Cont)main()main()

{{Number one(10); // Number one(10); // one.none.n = 10= 10one++; // one++; // one.none.n = 11= 11one.operator++(2); // one.operator++(2); // one.none.n = 13= 13

}}

There is no syntax for using the increment or decrement There is no syntax for using the increment or decrement operators to pass these values other than explicit invocation, aoperators to pass these values other than explicit invocation, as s shown in the preceding code. A more straightforward way to shown in the preceding code. A more straightforward way to implement this functionality is to overload the implement this functionality is to overload the addition/assignment operator (+=). addition/assignment operator (+=).

Page 26: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

26

Special Overloading Forms Special Overloading Forms A Few Operators Require Special Treatments During A Few Operators Require Special Treatments During

Overloading Overloading Conversion Operator Conversion Operator constconst Array Operator Array Operator Function Call Function Call ---- Parenthesis Operator 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 27: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

27

Overloading StreamOverloading Stream--Insertion and StreamInsertion and Stream--Extraction OperatorsExtraction Operators

Overloaded Overloaded << << andand >>>> operators operators Must have left operand of types Must have left operand of types ostreamostream &&, , istreamistream &&respectivelyrespectivelyIt must be a nonIt must be a non--member function (left operand not an 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 28: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

28

1 // Fig. 18.3: fig18_03.cpp

2 // Overloading the stream-insertion and

3 // stream-extraction operators.

4 #include <iostream>

5

6 using std::cout;

7 using std::cin;

8 using std::endl;

9 using std::ostream;

10 using std::istream;

11

12 #include <iomanip>

13

14 using std::setw;

15

16 class PhoneNumber {

17 friend ostream &operator<<( ostream&, const PhoneNumber & );

18 friend istream &operator>>( istream&, PhoneNumber & );

19

20 private:

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;).

29 ostream &operator<<( ostream &output, const PhoneNumber &num )

30 {

Page 29: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

29

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 30: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

30

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

Page 31: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

31

Example: Student ClassExample: Student Classclass Student {class Student {

public:public:

Student();Student();

Student( const string & id, const string & Student( const string & id, const string & lnamelname ););

boolbool operator <operator < (const Student & S2 );(const Student & S2 );

Student & Student & operator =operator =(const Student & S2 );(const Student & S2 );

boolbool operator ==operator ==( const Student & S2 );( const Student & S2 );

friend friend ostreamostream & & operator <<operator <<((ostreamostream & out, & out,

const Student & S);const Student & S);

friend friend istreamistream & & operator >>operator >>((istreamistream & & inpinp, Student & S);, Student & S);

private:private:

string string m_IDm_ID;;

string string m_LastNamem_LastName;;

};};

Page 32: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

32

Overloading <Overloading <

boolbool operator <( const Student & S2 ) operator <( const Student & S2 ) { { return return m_IDm_ID < S2.m_ID; < S2.m_ID;

}}

Page 33: Overloading · Overloading Operators— The Rules Associativity refers to the order in which actions within an ... Global Operator Overloading Similar to friend Function Overloading,

33

Overloading =Overloading =

Student & operator =( const Student & S2 ) Student & operator =( const Student & S2 ) {{// if assigning object to itself...// if assigning object to itself...if( *this == S2 )if( *this == S2 )

return *this;return *this;

m_IDm_ID = S2.m_ID;= S2.m_ID;m_LastNamem_LastName = S2.m_LastName;= S2.m_LastName;return *this;return *this;

}}