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

PPTX
Operator overloading
Garima Singh Makhija
 
PPTX
Operator overloading
ramya marichamy
 
PPT
Lecture#6 functions in c++
NUST Stuff
 
PPTX
Oops
ankush_kumar
 
PPT
Operator overloading
ArunaDevi63
 
PPTX
operator overloading
Nishant Joshi
 
PPT
14 operator overloading
Docent Education
 
PPTX
operator overloading
Sorath Peetamber
 
PPTX
Operator overloading
Kumar
 
PPT
FUNCTIONS IN c++ PPT
03062679929
 
PPTX
Operator overloading
Burhan Ahmed
 
PDF
03 function overloading
Jasleen Kaur (Chandigarh University)
 
PPTX
Learning C++ - Functions in C++ 3
Ali Aminian
 
PPT
Operator overloading
Northeastern University
 
PPTX
Functions in C++ (OOP)
Faizan Janjua
 
PPTX
C++ programming function
Vishalini Mugunen
 
PPTX
Inline Functions and Default arguments
Nikhil Pandit
 
PPTX
Operator overloading
Ramish Suleman
 
PDF
Operator overloading
Kamal Acharya
 
ODP
C++ Function
PingLun Liao
 
Operator overloading
Garima Singh Makhija
 
Operator overloading
ramya marichamy
 
Lecture#6 functions in c++
NUST Stuff
 
Operator overloading
ArunaDevi63
 
operator overloading
Nishant Joshi
 
14 operator overloading
Docent Education
 
operator overloading
Sorath Peetamber
 
Operator overloading
Kumar
 
FUNCTIONS IN c++ PPT
03062679929
 
Operator overloading
Burhan Ahmed
 
03 function overloading
Jasleen Kaur (Chandigarh University)
 
Learning C++ - Functions in C++ 3
Ali Aminian
 
Operator overloading
Northeastern University
 
Functions in C++ (OOP)
Faizan Janjua
 
C++ programming function
Vishalini Mugunen
 
Inline Functions and Default arguments
Nikhil Pandit
 
Operator overloading
Ramish Suleman
 
Operator overloading
Kamal Acharya
 
C++ Function
PingLun Liao
 

Similar to Overloading (20)

PDF
Lec 8.pdf a
aliashraf9689
 
PDF
M11 operator overloading and type conversion
NabeelaNousheen
 
PDF
Operator overloading
Pranali Chaudhari
 
PDF
overloading in C++
Prof Ansari
 
PDF
Ch-4-Operator Overloading.pdf
esuEthopi
 
PDF
Basics _of_Operator Overloading_Somesh_Kumar_SSTC
drsomeshdewangan
 
PPTX
3. Polymorphism.pptx
ChhaviCoachingCenter
 
PDF
Polymorphism and Type Conversion.pdf pot
e13225064
 
PPTX
Operator overloaing
zindadili
 
PPTX
Operator Overloading
Juginder Pal Singh
 
PPT
Operator overloading in c++ is the most required.
iammukesh1075
 
PPT
lecture12.ppt
UmairMughal74
 
PPT
OOP OOOOOverloading Concept lecture12.ppt
SriGovndarajaSwamyAr
 
PPT
operator overloading concept in oops lecture12.ppt
SriGovndarajaSwamyAr
 
PPT
Operator overloading
piyush Kumar Sharma
 
PPT
Synapse india complain sharing info on chapter 8 operator overloading
SynapseindiaComplaints
 
PPT
3d7b7 session4 c++
Mukund Trivedi
 
PPT
Lec 28 - operator overloading
Princess Sam
 
PPT
Lecture5
Sunil Gupta
 
PDF
Object Oriented Programming using C++ - Part 3
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Lec 8.pdf a
aliashraf9689
 
M11 operator overloading and type conversion
NabeelaNousheen
 
Operator overloading
Pranali Chaudhari
 
overloading in C++
Prof Ansari
 
Ch-4-Operator Overloading.pdf
esuEthopi
 
Basics _of_Operator Overloading_Somesh_Kumar_SSTC
drsomeshdewangan
 
3. Polymorphism.pptx
ChhaviCoachingCenter
 
Polymorphism and Type Conversion.pdf pot
e13225064
 
Operator overloaing
zindadili
 
Operator Overloading
Juginder Pal Singh
 
Operator overloading in c++ is the most required.
iammukesh1075
 
lecture12.ppt
UmairMughal74
 
OOP OOOOOverloading Concept lecture12.ppt
SriGovndarajaSwamyAr
 
operator overloading concept in oops lecture12.ppt
SriGovndarajaSwamyAr
 
Operator overloading
piyush Kumar Sharma
 
Synapse india complain sharing info on chapter 8 operator overloading
SynapseindiaComplaints
 
3d7b7 session4 c++
Mukund Trivedi
 
Lec 28 - operator overloading
Princess Sam
 
Lecture5
Sunil Gupta
 
Object Oriented Programming using C++ - Part 3
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Ad

Recently uploaded (20)

PDF
Sustainable and comertially viable mining process.pdf
Avijit Kumar Roy
 
PDF
HR agent at Mediq: Lessons learned on Agent Builder & Maestro by Tacstone Tec...
UiPathCommunity
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
"Effect, Fiber & Schema: tactical and technical characteristics of Effect.ts"...
Fwdays
 
PDF
OpenInfra ID 2025 - Are Containers Dying? Rethinking Isolation with MicroVMs.pdf
Muhammad Yuga Nugraha
 
PDF
Impact of IEEE Computer Society in Advancing Emerging Technologies including ...
Hironori Washizaki
 
PDF
Empowering Cloud Providers with Apache CloudStack and Stackbill
ShapeBlue
 
PPTX
Extensions Framework (XaaS) - Enabling Orchestrate Anything
ShapeBlue
 
PDF
HydITEx corporation Booklet 2025 English
Георгий Феодориди
 
PDF
Arcee AI - building and working with small language models (06/25)
Julien SIMON
 
PPTX
Building and Operating a Private Cloud with CloudStack and LINBIT CloudStack ...
ShapeBlue
 
PPT
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
PDF
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
PDF
Women in Automation Presents: Reinventing Yourself — Bold Career Pivots That ...
DianaGray10
 
PDF
Are there government-backed agri-software initiatives in Limerick.pdf
giselawagner2
 
PDF
Novus Safe Lite- What is Novus Safe Lite.pdf
Novus Hi-Tech
 
PPTX
The Yotta x CloudStack Advantage: Scalable, India-First Cloud
ShapeBlue
 
PDF
TrustArc Webinar - Data Privacy Trends 2025: Mid-Year Insights & Program Stra...
TrustArc
 
PDF
Building Resilience with Digital Twins : Lessons from Korea
SANGHEE SHIN
 
PPTX
Top Managed Service Providers in Los Angeles
Captain IT
 
Sustainable and comertially viable mining process.pdf
Avijit Kumar Roy
 
HR agent at Mediq: Lessons learned on Agent Builder & Maestro by Tacstone Tec...
UiPathCommunity
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
"Effect, Fiber & Schema: tactical and technical characteristics of Effect.ts"...
Fwdays
 
OpenInfra ID 2025 - Are Containers Dying? Rethinking Isolation with MicroVMs.pdf
Muhammad Yuga Nugraha
 
Impact of IEEE Computer Society in Advancing Emerging Technologies including ...
Hironori Washizaki
 
Empowering Cloud Providers with Apache CloudStack and Stackbill
ShapeBlue
 
Extensions Framework (XaaS) - Enabling Orchestrate Anything
ShapeBlue
 
HydITEx corporation Booklet 2025 English
Георгий Феодориди
 
Arcee AI - building and working with small language models (06/25)
Julien SIMON
 
Building and Operating a Private Cloud with CloudStack and LINBIT CloudStack ...
ShapeBlue
 
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
Women in Automation Presents: Reinventing Yourself — Bold Career Pivots That ...
DianaGray10
 
Are there government-backed agri-software initiatives in Limerick.pdf
giselawagner2
 
Novus Safe Lite- What is Novus Safe Lite.pdf
Novus Hi-Tech
 
The Yotta x CloudStack Advantage: Scalable, India-First Cloud
ShapeBlue
 
TrustArc Webinar - Data Privacy Trends 2025: Mid-Year Insights & Program Stra...
TrustArc
 
Building Resilience with Digital Twins : Lessons from Korea
SANGHEE SHIN
 
Top Managed Service Providers in Los Angeles
Captain IT
 
Ad

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