SlideShare une entreprise Scribd logo
1  sur  19
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
                 };

Contenu connexe

Tendances (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
 

Similaire à 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
 
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.
 
lecture12.ppt
lecture12.pptlecture12.ppt
lecture12.ppt
 
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
 
C
CC
C
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
 

Dernier

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 

Dernier (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 

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 };