SlideShare a Scribd company logo
Operator Overloading
   Reading: Chapter 8
Why overload operators?

• We can define new data types using classes.
• Member functions are invoked by sending
  messages.
• For many classes, this notation is
  cumbersome.
• For some classes, especially mathematical
  ones, it would be nice to be able to use
  operators with instances of these classes.
Example

• Suppose we have:
  – a class (called Time) for representing time of the day
  – two Time objects time1 and time2
• We want to be able to do things like
  – compare times
      if (time1 < time2)
  – print times to an output stream
      cout << "The first time is " << time1 << endl;
Simple example in C++

• The division operator / is used for
   – integer division
   – floating point division
• Actually performs two different types of
  division, but we use the same operator, i.e., it
  is overloaded.
• We will talk about how to overload or redefine
  our own operators for classes …
How to overload
                 operators?
• An overloaded operator is nothing but a
  – function
• The name of the function is the keyword
  operator followed by the symbol for the
  operator being overloaded.
• Example:
  – the function name operator+ would be
    used to overload the + operator.
Operators That Can Be
                     Overloaded

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

• Overloading an operator like + allows statements
  like:
        object1 + object2
• This does not allow statements like:
        object1 += object2
• The += operator must be overloaded separately.
• The "aritiy" (number of operands) of the operator
  cannot change.
Implementing operator
             overloading
• The functions must have access to the
  private member data of the class.
• Two ways to write operator overloading
  functions:
  – Member functions
  – Friend functions
Using member functions

• If the first operand of the operator is a class
  instance or a reference to a class instance, the
  overloaded operator can be implemented as a
  member function.
• Example invocation
      object = object1 + object2;
• Translated by compiler to
      object = object1.operator+(object2);
• When overloading (), [], -> or any of the
  assignment operators, the operator overloading
  function must be declared as a class member.
Example - Rational
                       Numbers
class Rational
{
   public:
      Rational(int n = 0, int d = 1);
      Rational operator+(const Rational &a) const;
      Rational operator-(const Rational &a) const;
      Rational operator*(const Rational &a) const;
   private:
      int numerator;
      int denominator;
}
Overloaded multiplication


Rational Rational::operator*(const Rational & a)
{
  int n = (*this).numerator * a.numerator;
  int d = (*this).denominator * a.denominator;
  return Rational(n,d);
}
Assignment

• Write the 2 other overloaded operators
  for the Rational class.
Rational Rational::operator+(const Rational & a)
{
  int commonD = denominator * a.denominator;
  int n = denominator * a. numerator +
          numerator * a. denominator;
  return Rational(n,commonD);
}
Using friend functions

• If the first operand of a binary operator is not
  a class instance nor a reference to a class
  instance, the overloaded operator can be
  implemented as a friend function
• Both operands are function arguments.
• Example invocation
      cout << object1;
• Translated by compiler to
      operator<<(cout,object1);
Example: Overloading
                  << and >>
• We often want to overload the insertion (>>) and extraction
  (<<) operators so that objects can be written and read using
  these operators.
• Phone number example: want to be able to read and write
  in format like
      (662) 325-7505
• Input statements might look like
      cin >> phone1;
• Output statements might look like
      cout << "My phone number is " << phone1 << endl;
Overloading << and >>

class PhoneNum
{
   friend ostream& operator<< (ostream&, const PhoneNum&);
   friend istream& operator>> (istream&, PhoneNum&);

     private:
        int areaCode;
        int prefix;
        int number;
};
Overloading << and >>

ostream& operator<< (ostream &output, const PhoneNum &num)
{
   output << "(" << num.areaCode << ") " << num.prefix <<
             "-" << num.number;
   return output;
};

istream& operator>> (istream &input, PhoneNum &num)
{
   input >> num.areaCode >> num.prefix >> num.number;
   return input;
};
Overloading << and >>

void main
{
   PhoneNum phone;
   cout << "Enter phone number like 999 325 0007" << endl;
   cin >> phone;
   cout << "The number is:" << phone << endl;
};
Assignment

• Rewrite the Time class to include overloaded operators for
  insertion, extraction, and comparison (>>, <<, and ==)

                 class Time {
                    public:
                        Time( );
                        void SetTime( int, int, int);
                        void PrintMilitary( );
                        void printStandard( );
                    private:
                        int hour;   // 0-23
                        int minute; // 0-59
                        int second; // 0-59
                 };

More Related Content

What's hot

Operator overloading
Operator overloadingOperator overloading
Operator overloading
Garima Singh Makhija
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
ramya marichamy
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
NUST Stuff
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
ArunaDevi63
 
operator overloading
operator overloadingoperator overloading
operator overloading
Nishant Joshi
 
14 operator overloading
14 operator overloading14 operator overloading
14 operator overloading
Docent Education
 
operator overloading
operator overloadingoperator overloading
operator overloading
Sorath Peetamber
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingKumar
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
03062679929
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
Burhan Ahmed
 
03 function overloading
03 function overloading03 function overloading
03 function overloading
Jasleen Kaur (Chandigarh University)
 
Learning C++ - Functions in C++ 3
Learning C++ - Functions  in C++ 3Learning C++ - Functions  in C++ 3
Learning C++ - Functions in C++ 3
Ali Aminian
 
Operator overloading
Operator overloading Operator overloading
Operator overloading
Northeastern University
 
Functions in C++ (OOP)
Functions in C++ (OOP)Functions in C++ (OOP)
Functions in C++ (OOP)
Faizan Janjua
 
C++ programming function
C++ programming functionC++ programming function
C++ programming function
Vishalini Mugunen
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
Nikhil Pandit
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
Ramish Suleman
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingKamal Acharya
 
C++ Function
C++ FunctionC++ Function
C++ Function
PingLun Liao
 

What's hot (20)

Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
 
Oops
OopsOops
Oops
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
operator overloading
operator overloadingoperator overloading
operator overloading
 
14 operator overloading
14 operator overloading14 operator overloading
14 operator overloading
 
operator overloading
operator overloadingoperator overloading
operator overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
03 function overloading
03 function overloading03 function overloading
03 function overloading
 
Learning C++ - Functions in C++ 3
Learning C++ - Functions  in C++ 3Learning C++ - Functions  in C++ 3
Learning C++ - Functions in C++ 3
 
Operator overloading
Operator overloading Operator overloading
Operator overloading
 
Functions in C++ (OOP)
Functions in C++ (OOP)Functions in C++ (OOP)
Functions in C++ (OOP)
 
C++ programming function
C++ programming functionC++ programming function
C++ programming function
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
C++ Function
C++ FunctionC++ Function
C++ Function
 

Similar to Overloading

Object Oriented Programming using C++ - Part 3
Object Oriented Programming using C++ - Part 3Object Oriented Programming using C++ - Part 3
Object Oriented Programming using C++ - Part 3
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
OOPS-Seminar.pdf
OOPS-Seminar.pdfOOPS-Seminar.pdf
OOPS-Seminar.pdf
Rithiga6
 
Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloadingPrincess Sam
 
lecture12.ppt
lecture12.pptlecture12.ppt
lecture12.ppt
UmairMughal74
 
Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.
iammukesh1075
 
Cpp (C++)
Cpp (C++)Cpp (C++)
Cpp (C++)
Jay Patel
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloadingPrincess Sam
 
c++ UNIT II.pptx
c++ UNIT II.pptxc++ UNIT II.pptx
overloading in C++
overloading in C++overloading in C++
overloading in C++
Prof Ansari
 
Week7a.pptx
Week7a.pptxWeek7a.pptx
Week7a.pptx
NasirAli233814
 
Ch-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdfCh-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdf
esuEthopi
 
Unit ii
Unit iiUnit ii
Unit ii
snehaarao19
 
Function
FunctionFunction
Function
yash patel
 
C++
C++C++
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
SynapseindiaComplaints
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Operator overloaing
Operator overloaingOperator overloaing
Operator overloaing
zindadili
 
Funtions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the topsFuntions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the tops
sameermhr345
 
C
CC

Similar to Overloading (20)

Object Oriented Programming using C++ - Part 3
Object Oriented Programming using C++ - Part 3Object Oriented Programming using C++ - Part 3
Object Oriented Programming using C++ - Part 3
 
OOPS-Seminar.pdf
OOPS-Seminar.pdfOOPS-Seminar.pdf
OOPS-Seminar.pdf
 
Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloading
 
lecture12.ppt
lecture12.pptlecture12.ppt
lecture12.ppt
 
Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.
 
Cpp (C++)
Cpp (C++)Cpp (C++)
Cpp (C++)
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloading
 
c++ UNIT II.pptx
c++ UNIT II.pptxc++ UNIT II.pptx
c++ UNIT II.pptx
 
overloading in C++
overloading in C++overloading in C++
overloading in C++
 
Week7a.pptx
Week7a.pptxWeek7a.pptx
Week7a.pptx
 
Ch-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdfCh-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdf
 
3d7b7 session4 c++
3d7b7 session4 c++3d7b7 session4 c++
3d7b7 session4 c++
 
Unit ii
Unit iiUnit ii
Unit ii
 
Function
FunctionFunction
Function
 
C++
C++C++
C++
 
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
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Operator overloaing
Operator overloaingOperator overloaing
Operator overloaing
 
Funtions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the topsFuntions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the tops
 
C
CC
C
 

Recently uploaded

Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 

Recently uploaded (20)

Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 

Overloading

  • 1. Operator Overloading Reading: Chapter 8
  • 2. Why overload operators? • We can define new data types using classes. • Member functions are invoked by sending messages. • For many classes, this notation is cumbersome. • For some classes, especially mathematical ones, it would be nice to be able to use operators with instances of these classes.
  • 3. Example • Suppose we have: – a class (called Time) for representing time of the day – two Time objects time1 and time2 • We want to be able to do things like – compare times if (time1 < time2) – print times to an output stream cout << "The first time is " << time1 << endl;
  • 4. Simple example in C++ • The division operator / is used for – integer division – floating point division • Actually performs two different types of division, but we use the same operator, i.e., it is overloaded. • We will talk about how to overload or redefine our own operators for classes …
  • 5. How to overload operators? • An overloaded operator is nothing but a – function • The name of the function is the keyword operator followed by the symbol for the operator being overloaded. • Example: – the function name operator+ would be used to overload the + operator.
  • 6. Operators That Can Be Overloaded + - * / % ^ & | ~ ! = < > += -= *= /= %= ^= &= |= << >> >>= <<= == != <= >= && || ++ -- ->* ‘ -> [] () new delete new [ ] delete [ ]
  • 7. Details • Overloading an operator like + allows statements like: object1 + object2 • This does not allow statements like: object1 += object2 • The += operator must be overloaded separately. • The "aritiy" (number of operands) of the operator cannot change.
  • 8. Implementing operator overloading • The functions must have access to the private member data of the class. • Two ways to write operator overloading functions: – Member functions – Friend functions
  • 9. Using member functions • If the first operand of the operator is a class instance or a reference to a class instance, the overloaded operator can be implemented as a member function. • Example invocation object = object1 + object2; • Translated by compiler to object = object1.operator+(object2); • When overloading (), [], -> or any of the assignment operators, the operator overloading function must be declared as a class member.
  • 10. Example - Rational Numbers class Rational { public: Rational(int n = 0, int d = 1); Rational operator+(const Rational &a) const; Rational operator-(const Rational &a) const; Rational operator*(const Rational &a) const; private: int numerator; int denominator; }
  • 11. Overloaded multiplication Rational Rational::operator*(const Rational & a) { int n = (*this).numerator * a.numerator; int d = (*this).denominator * a.denominator; return Rational(n,d); }
  • 12. Assignment • Write the 2 other overloaded operators for the Rational class.
  • 13. Rational Rational::operator+(const Rational & a) { int commonD = denominator * a.denominator; int n = denominator * a. numerator + numerator * a. denominator; return Rational(n,commonD); }
  • 14. Using friend functions • If the first operand of a binary operator is not a class instance nor a reference to a class instance, the overloaded operator can be implemented as a friend function • Both operands are function arguments. • Example invocation cout << object1; • Translated by compiler to operator<<(cout,object1);
  • 15. Example: Overloading << and >> • We often want to overload the insertion (>>) and extraction (<<) operators so that objects can be written and read using these operators. • Phone number example: want to be able to read and write in format like (662) 325-7505 • Input statements might look like cin >> phone1; • Output statements might look like cout << "My phone number is " << phone1 << endl;
  • 16. Overloading << and >> class PhoneNum { friend ostream& operator<< (ostream&, const PhoneNum&); friend istream& operator>> (istream&, PhoneNum&); private: int areaCode; int prefix; int number; };
  • 17. Overloading << and >> ostream& operator<< (ostream &output, const PhoneNum &num) { output << "(" << num.areaCode << ") " << num.prefix << "-" << num.number; return output; }; istream& operator>> (istream &input, PhoneNum &num) { input >> num.areaCode >> num.prefix >> num.number; return input; };
  • 18. Overloading << and >> void main { PhoneNum phone; cout << "Enter phone number like 999 325 0007" << endl; cin >> phone; cout << "The number is:" << phone << endl; };
  • 19. Assignment • Rewrite the Time class to include overloaded operators for insertion, extraction, and comparison (>>, <<, and ==) class Time { public: Time( ); void SetTime( int, int, int); void PrintMilitary( ); void printStandard( ); private: int hour; // 0-23 int minute; // 0-59 int second; // 0-59 };