08 c++ Operator Overloading.ppt

40
Overloading Operators Overloading Operators

Transcript of 08 c++ Operator Overloading.ppt

Page 1: 08 c++ Operator Overloading.ppt

Overloading OperatorsOverloading Operators

Page 2: 08 c++ Operator Overloading.ppt

Understanding the Benefits Understanding the Benefits of Overloadingof Overloading

► Having more than one function with the same Having more than one function with the same name is beneficial because you can use one name is beneficial because you can use one easy-to-understand function name without easy-to-understand function name without paying attention to the data types involvedpaying attention to the data types involved

► Polymorphism allows the same operation to Polymorphism allows the same operation to be carried out differently, depending on the be carried out differently, depending on the objectobject

► Some reserve the term polymorphism (or Some reserve the term polymorphism (or pure polymorphism) for situations in which pure polymorphism) for situations in which one function body is used with a variety of one function body is used with a variety of argumentsarguments

Page 3: 08 c++ Operator Overloading.ppt

Using the + Operator Using the + Operator PolymorphicallyPolymorphically

► Separate actions can result from what seems Separate actions can result from what seems to be the same operation or commandto be the same operation or command

► The + operator has a variety of meanings, The + operator has a variety of meanings, which include:which include: Alone before a value (called unary form), + indicates Alone before a value (called unary form), + indicates

a positive values, as in the expression +7a positive values, as in the expression +7

Between two integers (called binary form), + Between two integers (called binary form), + indicates integer addition, as in the expression 5+ 9indicates integer addition, as in the expression 5+ 9

Between two floating-point numbers (also called Between two floating-point numbers (also called binary form), + indicates floating-point addition, as binary form), + indicates floating-point addition, as in the expression 6.4 + 2.1in the expression 6.4 + 2.1

Page 4: 08 c++ Operator Overloading.ppt

Overloading Operators—Overloading Operators—The RulesThe Rules

► Operator overloading is the process by which Operator overloading is the process by which you apply operators to your own abstract data you apply operators to your own abstract data typestypes

► The +, -, *, and / symbols make it easy to work The +, -, *, and / symbols make it easy to work with built-in data types such as int and doublewith built-in data types such as int and double

► Classes, however, contain a variety of data Classes, however, contain a variety of data membersmembers

► As a result, if you want the compiler to perform As a result, if you want the compiler to perform arithmetic with two class objects, you must tell arithmetic with two class objects, you must tell the compiler what you meanthe compiler what you mean

► Good programming style dictates that you Good programming style dictates that you endow the operator with a reasonable meaningendow the operator with a reasonable meaning

Page 5: 08 c++ Operator Overloading.ppt

Overloading Operators—Overloading Operators—The RulesThe Rules

► You overload an operator by making it a function; You overload an operator by making it a function; subsequently, you can use it just like any other functionsubsequently, you can use it just like any other function

► C++ operators are classified as unary or binary, depending C++ operators are classified as unary or binary, depending on whether they take one or two arguments, respectivelyon whether they take one or two arguments, respectively

Page 6: 08 c++ Operator Overloading.ppt

Binary Operators that Can Binary Operators that Can Be OverloadedBe Overloaded

Page 7: 08 c++ Operator Overloading.ppt

Overloading Operators—Overloading Operators—The RulesThe Rules

► Associativity Associativity refers to the order refers to the order in which actions in which actions within an within an expression are expression are carried outcarried out

► You cannot You cannot change change associativity when associativity when you overload you overload operatorsoperators

► You also cannot You also cannot change the normal change the normal precedence of any precedence of any operatoroperator

Page 8: 08 c++ Operator Overloading.ppt

Overloading Operators—Overloading Operators—The RulesThe Rules

Page 9: 08 c++ Operator Overloading.ppt

Overloading Math OperatorsOverloading Math Operators

► When you code an expression such as 4 + 7, When you code an expression such as 4 + 7, C++ understands that you intend to carry out C++ understands that you intend to carry out binary integer addition because of the binary integer addition because of the context of the + symbolcontext of the + symbol

► When you code an expression such as When you code an expression such as regularSalregularSal + + bonusbonus, if C++ can recognize , if C++ can recognize regularSalregularSal and and bonusbonus as declared double as declared double variables, then floating-point addition takes variables, then floating-point addition takes placeplace

► The name of the operator function that The name of the operator function that overloads the + symbol is overloads the + symbol is operator+()operator+()

Page 10: 08 c++ Operator Overloading.ppt

Overloading Math OperatorsOverloading Math Operators

Ex8-1

Page 11: 08 c++ Operator Overloading.ppt

Overloading Math OperatorsOverloading Math Operators

► The operator+() function in Figure 8-1 can work The operator+() function in Figure 8-1 can work like any other member function like any other member function

► When you examine the code for the addTwo() When you examine the code for the addTwo() and operator+() functions in Figure 8-1, you see and operator+() functions in Figure 8-1, you see that the only difference is the function namethat the only difference is the function name

► Instead of the awkward Instead of the awkward sum = clerk.operator+sum = clerk.operator+(driver);,(driver);, the operator+() function allows you the operator+() function allows you to leave off the word operator in the function to leave off the word operator in the function name and add either of the following name and add either of the following statements:statements:sum = clerk + driver;sum = clerk + driver;

sum = driver + clerk;sum = driver + clerk;

Page 12: 08 c++ Operator Overloading.ppt

Overloading Math OperatorsOverloading Math Operators

Page 13: 08 c++ Operator Overloading.ppt

Paying Attention to the Paying Attention to the Order of the OperandsOrder of the Operands

► You can choose to overload any of the You can choose to overload any of the arithmetic operators for any classes you developarithmetic operators for any classes you develop

► Then you can use the corresponding operator Then you can use the corresponding operator symbol in a natural way with class objectssymbol in a natural way with class objects

Page 14: 08 c++ Operator Overloading.ppt

Overloading an Operator to Work with a Class Overloading an Operator to Work with a Class Object Object

and a Primitive Typeand a Primitive Type

► When you add two objects using the + operator, When you add two objects using the + operator, the objects do not have to be the same typethe objects do not have to be the same type

► You can add an integer and a double with an You can add an integer and a double with an expression such as 5 + 7.84expression such as 5 + 7.84

Ex8-3

Page 15: 08 c++ Operator Overloading.ppt

Overloading an Operator to Work with a Class Overloading an Operator to Work with a Class Object and a Primitive TypeObject and a Primitive Type

► You cannot overload operators that work You cannot overload operators that work with C++’s built-in data typeswith C++’s built-in data types

► You cannot overload the + that works with You cannot overload the + that works with two doubles to make it do anything but two doubles to make it do anything but add two doublesadd two doubles

► Similarly, you can’t overload operators Similarly, you can’t overload operators whose first operand is an object that is a whose first operand is an object that is a built-in type, even if the second operand built-in type, even if the second operand is a class objectis a class object

Page 16: 08 c++ Operator Overloading.ppt

Using Multiple Operations Using Multiple Operations in a Statementin a Statement

► Most modern programming languages allow Most modern programming languages allow several operators to be used in the same several operators to be used in the same statementstatement

► If you want to sum three values in an older If you want to sum three values in an older programming language such as assembler or programming language such as assembler or RPG, you first must add two values, producing RPG, you first must add two values, producing a temporary totala temporary total

► Then, in a separate statement, you add the Then, in a separate statement, you add the third value to that totalthird value to that total

Page 17: 08 c++ Operator Overloading.ppt

The Sale ClassThe Sale Class Ex8-4

Page 18: 08 c++ Operator Overloading.ppt

Using Multiple Operations Using Multiple Operations in a Statementin a Statement

► Because the associativity of addition occurs Because the associativity of addition occurs from left to right, the attempt to execute the from left to right, the attempt to execute the addition highlighted in Figure 8-9 follows this addition highlighted in Figure 8-9 follows this sequence:sequence:1.1.The left-most + operator is encountered, and C++ The left-most + operator is encountered, and C++

recognizes a Sale on each side of the + symbol. The recognizes a Sale on each side of the + symbol. The overloaded operator+() function is called, and overloaded operator+() function is called, and saleAmounts for a Shirt and a Tie are added. A saleAmounts for a Shirt and a Tie are added. A double is returneddouble is returned

2.2.The next + operator is encountered. A Sale object is The next + operator is encountered. A Sale object is found as the operand to the right of the +, but a found as the operand to the right of the +, but a double value is used as the operand to the leftdouble value is used as the operand to the left

Page 19: 08 c++ Operator Overloading.ppt

Program that Adds Three Program that Adds Three Sale ObjectsSale Objects Ex8-4

Page 20: 08 c++ Operator Overloading.ppt

Using Multiple Operations Using Multiple Operations in a Statementin a Statement

► When the Sale class operator+() function does not When the Sale class operator+() function does not return a double, but instead returns an object of return a double, but instead returns an object of Sale type (as shown in Figure 8-8), the multiple Sale type (as shown in Figure 8-8), the multiple addition works correctlyaddition works correctly

► The sequence of events now occurs as follows:The sequence of events now occurs as follows:

1.1. The left-most + operator is encountered, and C++ recognizes The left-most + operator is encountered, and C++ recognizes a Sale object on each side of the + symbol. The overloaded a Sale object on each side of the + symbol. The overloaded operator+() function is called, and saleAmounts for a Shirt operator+() function is called, and saleAmounts for a Shirt and a Tie are addedand a Tie are added

2.2. The next + operator is encountered. A Sale object now is The next + operator is encountered. A Sale object now is found on each side of the +—the temporary object returned found on each side of the +—the temporary object returned by the first addition, and the pants objectby the first addition, and the pants object

3.3. The temporary object is assigned to the total Sale objectThe temporary object is assigned to the total Sale object

Page 21: 08 c++ Operator Overloading.ppt

Using Multiple Operations in a Using Multiple Operations in a StatementStatement

► The results of the The results of the execution of the program execution of the program in Figure 8-9 are shown in Figure 8-9 are shown in Figure 8-10in Figure 8-10

► C++ forces you to use C++ forces you to use the built-in precedence the built-in precedence rules for your class rules for your class operatorsoperators

► If you want to be able to If you want to be able to add either a double or a add either a double or a Sale object to a Sale Sale object to a Sale object, then simply write object, then simply write both versions of the both versions of the overloaded operator for overloaded operator for the classthe class

Page 22: 08 c++ Operator Overloading.ppt

Overloading OutputOverloading Output

► The << operator also is overloaded by C++The << operator also is overloaded by C++► It is both a bitwise left-shift operator and an It is both a bitwise left-shift operator and an

output operator; it is called the insertion output operator; it is called the insertion operator when used for outputoperator when used for output

► The << operator acts as an output operator The << operator acts as an output operator only when only when coutcout (or another output stream (or another output stream object) appears on the left sideobject) appears on the left side

► When you use When you use coutcout in a program, you must in a program, you must include #include<iostream.h>include #include<iostream.h>

► The preceding function, called operator<<(), The preceding function, called operator<<(), returns a reference to ostreamreturns a reference to ostream

Page 23: 08 c++ Operator Overloading.ppt

Overloading OutputOverloading Output

► It accepts two arguments: a reference to It accepts two arguments: a reference to ostream (locally named ostream (locally named outout in this example) in this example) and an integer (locally named iand an integer (locally named inn in this in this example)example)

► C++ overloads the << operator to work with C++ overloads the << operator to work with the built-in data types; you also may overload the built-in data types; you also may overload the << operator to work with your own the << operator to work with your own classesclasses

► To overload << operator so it can work with a To overload << operator so it can work with a Sale object, you must add the overloaded Sale object, you must add the overloaded operator <<() function to the Sale classoperator <<() function to the Sale class

Page 24: 08 c++ Operator Overloading.ppt

Overloading OutputOverloading Output

► The operator <<() function is a friend to the The operator <<() function is a friend to the class of the object it wants to print out, e.g. class of the object it wants to print out, e.g. Sale here.Sale here.

Page 25: 08 c++ Operator Overloading.ppt

Overloading InputOverloading Input

► If the << operator can be overloaded for If the << operator can be overloaded for output, it makes sense that the >> operator output, it makes sense that the >> operator also can be overloaded for inputalso can be overloaded for input

► The advantage of overloading operators such The advantage of overloading operators such as >> is that the resulting programs look as >> is that the resulting programs look cleaner and are easier to readcleaner and are easier to read

► You can create an extraction operator, or You can create an extraction operator, or operator>>() function, that uses istream operator>>() function, that uses istream (which is defined in iostream.h, along with (which is defined in iostream.h, along with ostream) by using a prototype as follows:ostream) by using a prototype as follows:friend istream& operator>>(istream &in, Sale &Sale);friend istream& operator>>(istream &in, Sale &Sale);

Page 26: 08 c++ Operator Overloading.ppt

Overloaded Operator>>() Function for the Overloaded Operator>>() Function for the Sale ClassSale Class

Page 27: 08 c++ Operator Overloading.ppt

Overloading InputOverloading Input

Ex8-6

Page 28: 08 c++ Operator Overloading.ppt

Overloading ++ and - -Overloading ++ and - -► With C++, you use ++ to increment variables, With C++, you use ++ to increment variables,

and - - to decrement variablesand - - to decrement variables► When a prefix operator such as ++ is used in When a prefix operator such as ++ is used in

an expression, the mathematical operation an expression, the mathematical operation takes place before the expression is takes place before the expression is evaluatedevaluated

► When the postfix operator is used, the When the postfix operator is used, the expression is evaluated before the expression is evaluated before the mathematical operation takes placemathematical operation takes place

► Within the operator ++() function in the Within the operator ++() function in the Inventory class, you can write the statement Inventory class, you can write the statement that increases numSold in several different that increases numSold in several different waysways

Page 29: 08 c++ Operator Overloading.ppt

Using the Prefix and Postfix ++ Using the Prefix and Postfix ++ Operators with an IntegerOperators with an Integer

Page 30: 08 c++ Operator Overloading.ppt

The Inventory ClassThe Inventory Class

Page 31: 08 c++ Operator Overloading.ppt

Overloading ++ and - -Overloading ++ and - -

► The statements numSold++;, numSold = The statements numSold++;, numSold = numSold +1;, and numSold += 1; all would worknumSold +1;, and numSold += 1; all would work

8

Ex8-8

Page 32: 08 c++ Operator Overloading.ppt

Using Postfix Increment and Using Postfix Increment and Decrement OperatorsDecrement Operators

► A problem arises if you want to use a postfix A problem arises if you want to use a postfix ++ operator as well as a prefix ++ operator ++ operator as well as a prefix ++ operator with a classwith a class

► When you overload any C++ function, you When you overload any C++ function, you must supply different argument lists; for the must supply different argument lists; for the postfix ++ operator, you use an integer postfix ++ operator, you use an integer argumentargument

► The Inventory class postfix operator ++() The Inventory class postfix operator ++() function prototype is: function prototype is: Inventory& operator++(int);Inventory& operator++(int);

Ex8-8

Page 33: 08 c++ Operator Overloading.ppt

Overloading the = = OperatorOverloading the = = Operator

► Writing an operator = =() function should be Writing an operator = =() function should be an easy taskan easy task

► You simply decide what will constitute You simply decide what will constitute equality in class membersequality in class members

► When you create your own classes, you When you create your own classes, you choose whether equivalency means that choose whether equivalency means that every data field must be equivalent, or only every data field must be equivalent, or only specific data membersspecific data members

► The operator = =() function may return either The operator = =() function may return either an integer or a boolean variable representing an integer or a boolean variable representing true or falsetrue or false

8

Page 34: 08 c++ Operator Overloading.ppt

Overloading the = = OperatorOverloading the = = Operator

► A variable of type A variable of type boolbool can hold one of two values: can hold one of two values: true or falsetrue or false

► Some older C++ compilers do not support the bool Some older C++ compilers do not support the bool type; with those compilers you would use the first type; with those compilers you would use the first version of operator = =() that returns an integerversion of operator = =() that returns an integer

EX8-9

Page 35: 08 c++ Operator Overloading.ppt

Overloading the = OperatorOverloading the = Operator

► The = operator can be overloaded for use The = operator can be overloaded for use with your own classeswith your own classes

► Unlike other operators, if you don’t define the Unlike other operators, if you don’t define the = operator, C++ provides a definition for you= operator, C++ provides a definition for you

► If you want the = operator to do something If you want the = operator to do something other than assign each member, then you other than assign each member, then you must create a customer operator=()functionmust create a customer operator=()function

► In addition, if the class contains data fields In addition, if the class contains data fields that are pointers, you should create a custom that are pointers, you should create a custom functionfunction

EX8-9

Page 36: 08 c++ Operator Overloading.ppt

Overloading [ ] and ( )Overloading [ ] and ( )

► The The subscript operatorsubscript operator, operator[ ], is , operator[ ], is declared like any other function, but declared like any other function, but called in a manner similar to accessing called in a manner similar to accessing an array elementan array element

► You can include any instructions you You can include any instructions you want within an operator [ ] functionwant within an operator [ ] function

► Typically, you use this function to Typically, you use this function to perform a task that both requires an perform a task that both requires an argument and does not quite fit into argument and does not quite fit into another operator’s usual meaninganother operator’s usual meaning

Page 37: 08 c++ Operator Overloading.ppt

The Book ClassThe Book ClassEx8-10

Page 38: 08 c++ Operator Overloading.ppt

Overloading [ ] and ( )Overloading [ ] and ( )

Page 39: 08 c++ Operator Overloading.ppt

Using the Parentheses Using the Parentheses OperatorOperator

► You can use the You can use the parentheses operatorparentheses operator to make to make multiple assignments within a classmultiple assignments within a class

► To overload the parentheses operator to assign both To overload the parentheses operator to assign both an author and a price to a member of the Book class, an author and a price to a member of the Book class, you can create the functionyou can create the function

Page 40: 08 c++ Operator Overloading.ppt

Using the Parentheses Using the Parentheses OperatorOperator