SlideShare une entreprise Scribd logo
1  sur  4
08 c++ Operator Overloading.ppt — Presentation Transcript

1. Overloading Operators

2. Understanding the Benefits of Overloading Having more than one function with the same name is
beneficial because you can use one easy-to-understand function name without paying attention to the
data types involved Polymorphism allows the same operation to be carried out differently, depending
on the object Some reserve the term polymorphism (or pure polymorphism) for situations in which one
function body is used with a variety of arguments

3. Using the + Operator Polymorphically Separate actions can result from what seems to be the same
operation or command The + operator has a variety of meanings, which include: Alone before a value
(called unary form), + indicates a positive values, as in the expression +7 Between two integers (called
binary form), + indicates integer addition, as in the expression 5+ 9 Between two floating-point numbers
(also called binary form), + indicates floating-point addition, as in the expression 6.4 + 2.1

4. Overloading Operators— The Rules Operator overloading is the process by which you apply operators
to your own abstract data types The +, -, *, and / symbols make it easy to work with built-in data types
such as int and double Classes, however, contain a variety of data members As a result, if you want the
compiler to perform arithmetic with two class objects, you must tell the compiler what you mean Good
programming style dictates that you endow the operator with a reasonable meaning

5. Overloading Operators— The Rules You overload an operator by making it a function; subsequently,
you can use it just like any other function C++ operators are classified as unary or binary, depending on
whether they take one or two arguments, respectively

6. Binary Operators that Can Be Overloaded

7. Overloading Operators— The Rules Associativity refers to the order in which actions within an
expression are carried out You cannot change associativity when you overload operators You also
cannot change the normal precedence of any operator

8. Overloading Operators— The Rules

9. Overloading Math Operators When you code an expression such as 4 + 7, C++ understands that you
intend to carry out binary integer addition because of the context of the + symbol When you code an
expression such as regularSal + bonus , if C++ can recognize regularSal and bonus as declared double
variables, then floating-point addition takes place The name of the operator function that overloads the
+ symbol is operator+()

10. Overloading Math Operators Ex8-1

11. Overloading Math Operators The operator+() function in Figure 8-1 can work like any other member
function When you examine the code for the addTwo() and operator+() functions in Figure 8-1, you see
that the only difference is the function name Instead of the awkward sum = clerk.operator+(driver);, the
operator+() function allows you to leave off the word operator in the function name and add either of
the following statements: sum = clerk + driver; sum = driver + clerk;

12. Overloading Math Operators

13. Paying Attention to the Order of the Operands You can choose to overload any of the arithmetic
operators for any classes you develop Then you can use the corresponding operator symbol in a natural
way with class objects

14. Overloading an Operator to Work with a Class Object and a Primitive Type When you add two
objects using the + operator, the objects do not have to be the same type You can add an integer and a
double with an expression such as 5 + 7.84 Ex8-3

15. Overloading an Operator to Work with a Class Object and a Primitive Type You cannot overload
operators that work with C++’s built-in data types You cannot overload the + that works with two
doubles to make it do anything but add two doubles Similarly, you can’t overload operators whose first
operand is an object that is a built-in type, even if the second operand is a class object

16. Using Multiple Operations in a Statement Most modern programming languages allow several
operators to be used in the same statement If you want to sum three values in an older programming
language such as assembler or RPG, you first must add two values, producing a temporary total Then, in
a separate statement, you add the third value to that total

17. The Sale Class Ex8-4

18. Using Multiple Operations in a Statement Because the associativity of addition occurs from left to
right, the attempt to execute the addition highlighted in Figure 8-9 follows this sequence: 1. The left-
most + operator is encountered, and C++ recognizes a Sale on each side of the + symbol. The overloaded
operator+() function is called, and saleAmounts for a Shirt and a Tie are added. A double is returned 2.
The next + operator is encountered. A Sale object is found as the operand to the right of the +, but a
double value is used as the operand to the left

19. Program that Adds Three Sale Objects Ex8-4

20. Using Multiple Operations in a Statement When the Sale class operator+() function does not return a
double, but instead returns an object of Sale type (as shown in Figure 8-8), the multiple addition works
correctly The sequence of events now occurs as follows: 1. The left-most + operator is encountered, and
C++ recognizes a Sale object on each side of the + symbol. The overloaded operator+() function is called,
and saleAmounts for a Shirt and a Tie are added 2. The next + operator is encountered. A Sale object
now is found on each side of the +—the temporary object returned by the first addition, and the pants
object 3. The temporary object is assigned to the total Sale object

21. Using Multiple Operations in a Statement The results of the execution of the program in Figure 8-9
are shown in Figure 8-10 C++ forces you to use the built-in precedence rules for your class operators If
you want to be able to add either a double or a Sale object to a Sale object, then simply write both
versions of the overloaded operator for the class

22. Overloading Output The << operator also is overloaded by C++ It is both a bitwise left-shift operator
and an output operator; it is called the insertion operator when used for output The << operator acts as
an output operator only when cout (or another output stream object) appears on the left side When you
use cout in a program, you must include #include<iostream.h> The preceding function, called
operator<<(), returns a reference to ostream

23. Overloading Output It accepts two arguments: a reference to ostream (locally named out in this
example) and an integer (locally named i n in this example) C++ overloads the << operator to work with
the built-in data types; you also may overload the << operator to work with your own classes To
overload << operator so it can work with a Sale object, you must add the overloaded operator <<()
function to the Sale class

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

25. Overloading Input If the << operator can be overloaded for output, it makes sense that the >>
operator also can be overloaded for input The advantage of overloading operators such as >> is that the
resulting programs look cleaner and are easier to read You can create an extraction operator, or
operator>>() function, that uses istream (which is defined in iostream.h, along with ostream) by using a
prototype as follows: friend istream& operator>>(istream &in, Sale &Sale);

26. Overloaded Operator>>() Function for the Sale Class

27. Overloading Input Ex8-6

28. Overloading ++ and - - With C++, you use ++ to increment variables, and - - to decrement variables
When a prefix operator such as ++ is used in an expression, the mathematical operation takes place
before the expression is evaluated When the postfix operator is used, the expression is evaluated before
the mathematical operation takes place Within the operator ++() function in the Inventory class, you can
write the statement that increases numSold in several different ways

29. Using the Prefix and Postfix ++ Operators with an Integer

30. The Inventory Class

31. Overloading ++ and - - The statements numSold++;, numSold = numSold +1;, and numSold += 1; all
would work 8 Ex8-8

32. Using Postfix Increment and Decrement Operators A problem arises if you want to use a postfix ++
operator as well as a prefix ++ operator with a class When you overload any C++ function, you must
supply different argument lists; for the postfix ++ operator, you use an integer argument The Inventory
class postfix operator ++() function prototype is: Inventory& operator++(int); Ex8-8
33. Overloading the = = Operator Writing an operator = =() function should be an easy task You simply
decide what will constitute equality in class members When you create your own classes, you choose
whether equivalency means that every data field must be equivalent, or only specific data members The
operator = =() function may return either an integer or a boolean variable representing true or false 8

34. Overloading the = = Operator A variable of type bool can hold one of two values: true or false Some
older C++ compilers do not support the bool type; with those compilers you would use the first version
of operator = =() that returns an integer EX8-9


35. Overloading the = Operator The = operator can be overloaded for use with your own classes Unlike
other operators, if you don’t define the = operator, C++ provides a definition for you If you want the =
operator to do something other than assign each member, then you must create a customer
operator=()function In addition, if the class contains data fields that are pointers, you should create a
custom function EX8-9

36. Overloading [ ] and ( ) The subscript operator , operator[ ], is declared like any other function, but
called in a manner similar to accessing an array element You can include any instructions you want
within an operator [ ] function Typically, you use this function to perform a task that both requires an
argument and does not quite fit into another operator’s usual meaning

37. The Book Class Ex8-10

38. Overloading [ ] and ( )

39. Using the Parentheses Operator You can use the parentheses operator to make multiple
assignments within a class To overload the parentheses operator to assign both an author and a price to
a member of the Book class, you can create the function

40. Using the Parentheses Operator

Contenu connexe

Tendances

Operator overloading
Operator overloadingOperator overloading
Operator overloadingfarhan amjad
 
01. introduction to C++
01. introduction to C++01. introduction to C++
01. introduction to C++Haresh Jaiswal
 
Csc1100 lecture02 ch02-datatype_declaration
Csc1100 lecture02 ch02-datatype_declarationCsc1100 lecture02 ch02-datatype_declaration
Csc1100 lecture02 ch02-datatype_declarationIIUM
 
Csc1100 lecture05 ch05
Csc1100 lecture05 ch05Csc1100 lecture05 ch05
Csc1100 lecture05 ch05IIUM
 
Csc1100 lecture06 ch06_pt1
Csc1100 lecture06 ch06_pt1Csc1100 lecture06 ch06_pt1
Csc1100 lecture06 ch06_pt1IIUM
 
C++ overloading
C++ overloadingC++ overloading
C++ overloadingsanya6900
 
Csc1100 lecture06 ch06_pt2
Csc1100 lecture06 ch06_pt2Csc1100 lecture06 ch06_pt2
Csc1100 lecture06 ch06_pt2IIUM
 
Synapse india complain sharing info on chapter 8 operator overloading
Synapse india complain sharing info on chapter 8   operator overloadingSynapse india complain sharing info on chapter 8   operator overloading
Synapse india complain sharing info on chapter 8 operator overloadingSynapseindiaComplaints
 
Csc1100 lecture04 ch04
Csc1100 lecture04 ch04Csc1100 lecture04 ch04
Csc1100 lecture04 ch04IIUM
 
Input and output in c++
Input and output in c++Input and output in c++
Input and output in c++Asaye Dilbo
 
Functions in c++
Functions in c++Functions in c++
Functions in c++Asaye Dilbo
 
Operator overloading in C++
Operator overloading in C++Operator overloading in C++
Operator overloading in C++Ilio Catallo
 
Lab exam 5_5_15
Lab exam 5_5_15Lab exam 5_5_15
Lab exam 5_5_15Daman Toor
 
basics of C and c++ by eteaching
basics of C and c++ by eteachingbasics of C and c++ by eteaching
basics of C and c++ by eteachingeteaching
 
computer notes - Reference variables ii
computer notes - Reference variables iicomputer notes - Reference variables ii
computer notes - Reference variables iiecomputernotes
 

Tendances (20)

Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
01. introduction to C++
01. introduction to C++01. introduction to C++
01. introduction to C++
 
Csc1100 lecture02 ch02-datatype_declaration
Csc1100 lecture02 ch02-datatype_declarationCsc1100 lecture02 ch02-datatype_declaration
Csc1100 lecture02 ch02-datatype_declaration
 
Csc1100 lecture05 ch05
Csc1100 lecture05 ch05Csc1100 lecture05 ch05
Csc1100 lecture05 ch05
 
Csc1100 lecture06 ch06_pt1
Csc1100 lecture06 ch06_pt1Csc1100 lecture06 ch06_pt1
Csc1100 lecture06 ch06_pt1
 
Manipulators
ManipulatorsManipulators
Manipulators
 
C++ overloading
C++ overloadingC++ overloading
C++ overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Csc1100 lecture06 ch06_pt2
Csc1100 lecture06 ch06_pt2Csc1100 lecture06 ch06_pt2
Csc1100 lecture06 ch06_pt2
 
Synapse india complain sharing info on chapter 8 operator overloading
Synapse india complain sharing info on chapter 8   operator overloadingSynapse india complain sharing info on chapter 8   operator overloading
Synapse india complain sharing info on chapter 8 operator overloading
 
Csc1100 lecture04 ch04
Csc1100 lecture04 ch04Csc1100 lecture04 ch04
Csc1100 lecture04 ch04
 
Input and output in c++
Input and output in c++Input and output in c++
Input and output in c++
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Operator overloading in C++
Operator overloading in C++Operator overloading in C++
Operator overloading in C++
 
C++
C++C++
C++
 
Lab exam 5_5_15
Lab exam 5_5_15Lab exam 5_5_15
Lab exam 5_5_15
 
Manipulators
ManipulatorsManipulators
Manipulators
 
basics of C and c++ by eteaching
basics of C and c++ by eteachingbasics of C and c++ by eteaching
basics of C and c++ by eteaching
 
computer notes - Reference variables ii
computer notes - Reference variables iicomputer notes - Reference variables ii
computer notes - Reference variables ii
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 

En vedette

OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++Aabha Tiwari
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singhdheeraj_cse
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: InheritanceTareq Hasan
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)Ritika Sharma
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPTPooja Jaiswal
 
operator overloading in c++
operator overloading in c++operator overloading in c++
operator overloading in c++harman kaur
 

En vedette (7)

OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singh
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
operator overloading in c++
operator overloading in c++operator overloading in c++
operator overloading in c++
 

Similaire à Operator Overloading in C

Similaire à Operator Overloading in C (20)

08 c-operator-overloadingppt2563
08 c-operator-overloadingppt256308 c-operator-overloadingppt2563
08 c-operator-overloadingppt2563
 
Ch-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdfCh-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdf
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
overloading in C++
overloading in C++overloading in C++
overloading in C++
 
Oops
OopsOops
Oops
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloading
 
Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloading
 
Operator overloading in C++
Operator  overloading in C++Operator  overloading in C++
Operator overloading in C++
 
Binary operator overloading
Binary operator overloadingBinary operator overloading
Binary operator overloading
 
Chapter24 operator-overloading
Chapter24 operator-overloadingChapter24 operator-overloading
Chapter24 operator-overloading
 
NIKUL SURANI
NIKUL SURANINIKUL SURANI
NIKUL SURANI
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Programming presentation
Programming presentationProgramming presentation
Programming presentation
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
C++.pptx
C++.pptxC++.pptx
C++.pptx
 
Operator overloaing
Operator overloaingOperator overloaing
Operator overloaing
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Week7a.pptx
Week7a.pptxWeek7a.pptx
Week7a.pptx
 

Dernier

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 

Dernier (20)

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 

Operator Overloading in C

  • 1. 08 c++ Operator Overloading.ppt — Presentation Transcript 1. Overloading Operators 2. Understanding the Benefits of Overloading Having more than one function with the same name is beneficial because you can use one easy-to-understand function name without paying attention to the data types involved Polymorphism allows the same operation to be carried out differently, depending on the object Some reserve the term polymorphism (or pure polymorphism) for situations in which one function body is used with a variety of arguments 3. Using the + Operator Polymorphically Separate actions can result from what seems to be the same operation or command The + operator has a variety of meanings, which include: Alone before a value (called unary form), + indicates a positive values, as in the expression +7 Between two integers (called binary form), + indicates integer addition, as in the expression 5+ 9 Between two floating-point numbers (also called binary form), + indicates floating-point addition, as in the expression 6.4 + 2.1 4. Overloading Operators— The Rules Operator overloading is the process by which you apply operators to your own abstract data types The +, -, *, and / symbols make it easy to work with built-in data types such as int and double Classes, however, contain a variety of data members As a result, if you want the compiler to perform arithmetic with two class objects, you must tell the compiler what you mean Good programming style dictates that you endow the operator with a reasonable meaning 5. Overloading Operators— The Rules You overload an operator by making it a function; subsequently, you can use it just like any other function C++ operators are classified as unary or binary, depending on whether they take one or two arguments, respectively 6. Binary Operators that Can Be Overloaded 7. Overloading Operators— The Rules Associativity refers to the order in which actions within an expression are carried out You cannot change associativity when you overload operators You also cannot change the normal precedence of any operator 8. Overloading Operators— The Rules 9. Overloading Math Operators When you code an expression such as 4 + 7, C++ understands that you intend to carry out binary integer addition because of the context of the + symbol When you code an expression such as regularSal + bonus , if C++ can recognize regularSal and bonus as declared double variables, then floating-point addition takes place The name of the operator function that overloads the + symbol is operator+() 10. Overloading Math Operators Ex8-1 11. Overloading Math Operators The operator+() function in Figure 8-1 can work like any other member function When you examine the code for the addTwo() and operator+() functions in Figure 8-1, you see that the only difference is the function name Instead of the awkward sum = clerk.operator+(driver);, the
  • 2. operator+() function allows you to leave off the word operator in the function name and add either of the following statements: sum = clerk + driver; sum = driver + clerk; 12. Overloading Math Operators 13. Paying Attention to the Order of the Operands You can choose to overload any of the arithmetic operators for any classes you develop Then you can use the corresponding operator symbol in a natural way with class objects 14. Overloading an Operator to Work with a Class Object and a Primitive Type When you add two objects using the + operator, the objects do not have to be the same type You can add an integer and a double with an expression such as 5 + 7.84 Ex8-3 15. Overloading an Operator to Work with a Class Object and a Primitive Type You cannot overload operators that work with C++’s built-in data types You cannot overload the + that works with two doubles to make it do anything but add two doubles Similarly, you can’t overload operators whose first operand is an object that is a built-in type, even if the second operand is a class object 16. Using Multiple Operations in a Statement Most modern programming languages allow several operators to be used in the same statement If you want to sum three values in an older programming language such as assembler or RPG, you first must add two values, producing a temporary total Then, in a separate statement, you add the third value to that total 17. The Sale Class Ex8-4 18. Using Multiple Operations in a Statement Because the associativity of addition occurs from left to right, the attempt to execute the addition highlighted in Figure 8-9 follows this sequence: 1. The left- most + operator is encountered, and C++ recognizes a Sale on each side of the + symbol. The overloaded operator+() function is called, and saleAmounts for a Shirt and a Tie are added. A double is returned 2. The next + operator is encountered. A Sale object is found as the operand to the right of the +, but a double value is used as the operand to the left 19. Program that Adds Three Sale Objects Ex8-4 20. Using Multiple Operations in a Statement When the Sale class operator+() function does not return a double, but instead returns an object of Sale type (as shown in Figure 8-8), the multiple addition works correctly The sequence of events now occurs as follows: 1. The left-most + operator is encountered, and C++ recognizes a Sale object on each side of the + symbol. The overloaded operator+() function is called, and saleAmounts for a Shirt and a Tie are added 2. The next + operator is encountered. A Sale object now is found on each side of the +—the temporary object returned by the first addition, and the pants object 3. The temporary object is assigned to the total Sale object 21. Using Multiple Operations in a Statement The results of the execution of the program in Figure 8-9 are shown in Figure 8-10 C++ forces you to use the built-in precedence rules for your class operators If
  • 3. you want to be able to add either a double or a Sale object to a Sale object, then simply write both versions of the overloaded operator for the class 22. Overloading Output The << operator also is overloaded by C++ It is both a bitwise left-shift operator and an output operator; it is called the insertion operator when used for output The << operator acts as an output operator only when cout (or another output stream object) appears on the left side When you use cout in a program, you must include #include<iostream.h> The preceding function, called operator<<(), returns a reference to ostream 23. Overloading Output It accepts two arguments: a reference to ostream (locally named out in this example) and an integer (locally named i n in this example) C++ overloads the << operator to work with the built-in data types; you also may overload the << operator to work with your own classes To overload << operator so it can work with a Sale object, you must add the overloaded operator <<() function to the Sale class 24. Overloading Output The operator <<() function is a friend to the class of the object it wants to print out, e.g. Sale here. 25. Overloading Input If the << operator can be overloaded for output, it makes sense that the >> operator also can be overloaded for input The advantage of overloading operators such as >> is that the resulting programs look cleaner and are easier to read You can create an extraction operator, or operator>>() function, that uses istream (which is defined in iostream.h, along with ostream) by using a prototype as follows: friend istream& operator>>(istream &in, Sale &Sale); 26. Overloaded Operator>>() Function for the Sale Class 27. Overloading Input Ex8-6 28. Overloading ++ and - - With C++, you use ++ to increment variables, and - - to decrement variables When a prefix operator such as ++ is used in an expression, the mathematical operation takes place before the expression is evaluated When the postfix operator is used, the expression is evaluated before the mathematical operation takes place Within the operator ++() function in the Inventory class, you can write the statement that increases numSold in several different ways 29. Using the Prefix and Postfix ++ Operators with an Integer 30. The Inventory Class 31. Overloading ++ and - - The statements numSold++;, numSold = numSold +1;, and numSold += 1; all would work 8 Ex8-8 32. Using Postfix Increment and Decrement Operators A problem arises if you want to use a postfix ++ operator as well as a prefix ++ operator with a class When you overload any C++ function, you must supply different argument lists; for the postfix ++ operator, you use an integer argument The Inventory class postfix operator ++() function prototype is: Inventory& operator++(int); Ex8-8
  • 4. 33. Overloading the = = Operator Writing an operator = =() function should be an easy task You simply decide what will constitute equality in class members When you create your own classes, you choose whether equivalency means that every data field must be equivalent, or only specific data members The operator = =() function may return either an integer or a boolean variable representing true or false 8 34. Overloading the = = Operator A variable of type bool can hold one of two values: true or false Some older C++ compilers do not support the bool type; with those compilers you would use the first version of operator = =() that returns an integer EX8-9 35. Overloading the = Operator The = operator can be overloaded for use with your own classes Unlike other operators, if you don’t define the = operator, C++ provides a definition for you If you want the = operator to do something other than assign each member, then you must create a customer operator=()function In addition, if the class contains data fields that are pointers, you should create a custom function EX8-9 36. Overloading [ ] and ( ) The subscript operator , operator[ ], is declared like any other function, but called in a manner similar to accessing an array element You can include any instructions you want within an operator [ ] function Typically, you use this function to perform a task that both requires an argument and does not quite fit into another operator’s usual meaning 37. The Book Class Ex8-10 38. Overloading [ ] and ( ) 39. Using the Parentheses Operator You can use the parentheses operator to make multiple assignments within a class To overload the parentheses operator to assign both an author and a price to a member of the Book class, you can create the function 40. Using the Parentheses Operator