SlideShare a Scribd company logo
1 of 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
                 };

More Related Content

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

Recently uploaded

Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
🐬 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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
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
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
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
 

Recently uploaded (20)

Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
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?
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
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
 

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