SlideShare uma empresa Scribd logo
1 de 11
Lecture 17



Operator Overloading



                       1
Introduction

A number of predefined operators can be applied to the built-
in standard types.


These operators can be overloaded, means each of them can
be used for several standard types.



For example: operator + operates on int, float and
double. So + is already OverLoaded ( same interface but
different implementations)
Can + --- ADD A & B
Adding additional processing power to the operator.2
Introduction

The operators that can be overloaded are
+     -     *      /     %     ^     &     |        ~    !
=     <     >      +=    -=    *=    /=    %=       ^=
&=    |=    <<     >>    >>= <<= ==        !=       <=
>=    &&    ||     ++   --    ->*    ,     ->       []
()    new   delete      new[] delete[]


The operators that cannot be overloaded are

.     .*    ::    ?:    sizeof

                                                3
Overloading the assignment operator
                        (=)

Purpose of assignment operator is to copy one object or
value to another.

Similar to the default constructor, the copy constructor,
and the destructor, the assignment operator is created
automatically for every class that is defined.

But also the assignment operator can be defined
explicitly in the class definition.

How to overload operator?
Write a function with the keyword operatorX, where X is
an operator symbol. For example: operator=
                                             4
Sample program to overload
                   assignment operator (1st. version)
#include<iostream.h>                          void main()
class Rational {                              { Rational x(22,7), z;
 public:                                          x.print(); cout<<endl;
    Rational (int=0, int=1);                      z.print(); cout<<endl;
    void operator=(const Rational&);              z = x;
   void print() { cout << num << '/’ << den       x.print(); cout<<endl;
   << endl;}                                      z.print(); cout<<endl;
 private:                                     } //end main block
    int num;
    int den;                                                Output:
};
                                                                           22/7
Rational::Rational(int n, int d)                                           0/1
{ num = n;                                                                 22/7
  den = d; } // end Rational::Rational()                                   22/7
void Rational::operator=(const Rational& r)   This version does not check for
{ num = r.num;
    den = r.den;                              self assignment (z=z) and allow
} // end Rational::operator=()                chained assignments (z = x = y).
                                                                     5
Sample program to overload
         assignment operator (1st. version)
                                   Rational::Rational(int n=0, int d=1)
                                   { num = n;
             z               x       den = d; } // end Rational::Rational()



          num = 0       num = 22

          den = 1       den = 7



                       void Rational::operator=(const Rational& r)
Rational x(22,7), z;   { num = r.num;
                           den = r.den;
z   =   x;             } // end Rational::operator=()

                                                        6
Sample program to overload
                  assignment operator (2nd. version)
#include<iostream.h>                          Rational Rational::operator= (const Rational& r)
class Rational {                              { num = r.num;
 public:                                        den = r.den;
    Rational (int=0, int=1);                    return *this; }// end Rational::operator=
    Ratinal operator=(const Rational&);
   void print() { cout << num << '/’ << den   void main()
   << endl;}                                  { Rational x(22,7), y(-3,8), z;
 private:                                        x.print(); cout<<endl;         // prints 22/7
    int num;                                     y.print(); cout<<endl;         // prints -3/8
    int den;                                     z.print(); cout<<endl;         // prints 0/1
};                                               z = x = y;
                                                 x.print(); cout<<endl;         // prints -3/8
Rational::Rational(int n, int d)                 y.print(); cout<<endl;          // prints -3/8
{ num = n;                                       z.print(); cout<<endl;          // prints -3/8
  den = d; }// end Rational::Rational
                                              } //end main block




                                                                                 7
Sample program to overload
             assignment operator (1st. version)


       z                    x                          y

    num = 0              num = 22                  num = -3

    den = 1              den = 7                   den = 8



                                   void Rational::operator=(const Rational& r)
Rational x(22,7), y(-3,8); z;      { num = r.num;
                                       den = r.den;
   z    =   x   =   y;                 return *this;
                                   } // end Rational::operator=()
                                                                 8
Overloading the arithmetic operators
                              (+, -, *, /)
#include<iostream.h>                             void Rational::operator=(const Rational& r)
class Rational {                                 { num = r.num;
                                                     den = r.den;
 friend Rational operator* (const Rational&,
                                                     return this;
 const Rational&);
                                                 } // end Rational::operator=()
 public:
    Rational (int=0, int=1);
                                                 void main()
    Rational operator=(const Rational&);
                                                 { Rational a(22,7), b(-3, 8), c;
   void print() { cout << num << '/’ << den
                                                     c = a;
   << endl;}
                                                     c.print(); cout<<endl;         //prints 22/7
 private:
    int num;                                         c = a * b;
    int den;                                         c.print(); cout<<endl;         //prints -66/42
};                                               } //end main block
                                                 Note:
Rational operator*(const Rational& x, const
                                                 •The operator* function is not a
Rational& y)
{ Rational result;                               member function of class Rational but
  result.num = x.num * y.num;                    as a friend of the class Rational.
  result.den = x.den * y.den;                    •The operator* function requires two
  return result; } // end Rational operator*()
                                                 arguments.               9
Sample program to overload
             assignment operator (1st. version)


       c                    a                             b

    num = 0              num = 22           *        num = -3

    den = 1              den = 7            *        den = 8



                                Rational operator*(const Rational& x, const Rational& y)
Rational a(22,7), b(-3,8); c;   { Rational result;
                                  result.num = x.num * y.num;
                                  result.den = x.den * y.den;
   c    =   a   *   b;            return result; } // end Rational operator*()

                                                                     10
Overloading the arithmetic assignment
                     operators (+=, -=, *=, /=)
#include<iostream.h>                              void Rational::operator=(const Rational& r)
class Rational {                                  { num = r.num;
public:                                               den = r.den;
    Rational (int=0, int=1);                          return *this;
    Rational operator=(const Rational&);          } // end Rational::operator=()
    Rational operator*=(const Rational&);
   void print() { cout << num << '/’ << den       void main()
   << endl;}                                      { Rational frac1(22,7), frac2(-3, 8), frac3;
 private:                                             frac3 = frac1;
    int num;                                          frac3.print(); cout<<endl;    //prints 22/7
    int den;                                          frac1 *= frac2;
};                                                    frac1.print(); cout<<endl;    //prints -66/42
                                                  } //end main block
Rational Rational::operator*= (const
Rational& x )                                     By returning *this, the operator can be
{ num = num * x.num;                              chained, like:  x *= y *= z;
  den = den * x.den;
  return *this; } // end Rational::operator*=()


                                                                                 11

Mais conteúdo relacionado

Mais procurados (20)

functions
functionsfunctions
functions
 
ฟังก์ชั่นย่อยและโปรแกรมมาตรฐาน ม. 6 1
ฟังก์ชั่นย่อยและโปรแกรมมาตรฐาน ม. 6  1ฟังก์ชั่นย่อยและโปรแกรมมาตรฐาน ม. 6  1
ฟังก์ชั่นย่อยและโปรแกรมมาตรฐาน ม. 6 1
 
Fun with functions
Fun with functionsFun with functions
Fun with functions
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
03 function overloading
03 function overloading03 function overloading
03 function overloading
 
FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3
 
OpenGL SC 2.0 Quick Reference
OpenGL SC 2.0 Quick ReferenceOpenGL SC 2.0 Quick Reference
OpenGL SC 2.0 Quick Reference
 
OpenGL 4.6 Reference Guide
OpenGL 4.6 Reference GuideOpenGL 4.6 Reference Guide
OpenGL 4.6 Reference Guide
 
functions of C++
functions of C++functions of C++
functions of C++
 
C++ Pointers
C++ PointersC++ Pointers
C++ Pointers
 
OpenGL ES 3.2 Reference Guide
OpenGL ES 3.2 Reference GuideOpenGL ES 3.2 Reference Guide
OpenGL ES 3.2 Reference Guide
 
C++11
C++11C++11
C++11
 
Constructor
ConstructorConstructor
Constructor
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 
C++ programming function
C++ programming functionC++ programming function
C++ programming function
 
Giorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrency
 
Vulkan 1.1 Reference Guide
Vulkan 1.1 Reference GuideVulkan 1.1 Reference Guide
Vulkan 1.1 Reference Guide
 
C and C++ functions
C and C++ functionsC and C++ functions
C and C++ functions
 
OpenCL 2.1 Reference Guide
OpenCL 2.1 Reference GuideOpenCL 2.1 Reference Guide
OpenCL 2.1 Reference Guide
 

Destaque (13)

Lecture20
Lecture20Lecture20
Lecture20
 
Lecture21
Lecture21Lecture21
Lecture21
 
Facebook經營觀察 0820
Facebook經營觀察 0820Facebook經營觀察 0820
Facebook經營觀察 0820
 
Springwood at music resonate
Springwood at music resonateSpringwood at music resonate
Springwood at music resonate
 
Lecture16
Lecture16Lecture16
Lecture16
 
Lecture07
Lecture07Lecture07
Lecture07
 
Lecture10
Lecture10Lecture10
Lecture10
 
Lecture09
Lecture09Lecture09
Lecture09
 
Writs and Contracts Presentation
Writs and Contracts PresentationWrits and Contracts Presentation
Writs and Contracts Presentation
 
Lecture05
Lecture05Lecture05
Lecture05
 
Principles of Natural Justice & The Indian Constitution.
Principles of Natural Justice & The Indian Constitution.Principles of Natural Justice & The Indian Constitution.
Principles of Natural Justice & The Indian Constitution.
 
Structure of Indian judiciary
Structure of Indian judiciaryStructure of Indian judiciary
Structure of Indian judiciary
 
Judiciary System in India
Judiciary System in IndiaJudiciary System in India
Judiciary System in India
 

Semelhante a Operator Overloading: Lecture 17

Lecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handlingLecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handlingHariz Mustafa
 
#ifndef RATIONAL_H   if this compiler macro is not defined #def.pdf
#ifndef RATIONAL_H    if this compiler macro is not defined #def.pdf#ifndef RATIONAL_H    if this compiler macro is not defined #def.pdf
#ifndef RATIONAL_H   if this compiler macro is not defined #def.pdfexxonzone
 
write the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdfwrite the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdfjyothimuppasani1
 
User defined functions
User defined functionsUser defined functions
User defined functionsshubham_jangid
 
PROGRAM 2 – Fraction Class Problem For this programming as.pdf
PROGRAM 2 – Fraction Class Problem For this programming as.pdfPROGRAM 2 – Fraction Class Problem For this programming as.pdf
PROGRAM 2 – Fraction Class Problem For this programming as.pdfezonesolutions
 
AnswerNote Provided code shows several bugs, hence I implemented.pdf
AnswerNote Provided code shows several bugs, hence I implemented.pdfAnswerNote Provided code shows several bugs, hence I implemented.pdf
AnswerNote Provided code shows several bugs, hence I implemented.pdfanurag1231
 
Part 3-functions
Part 3-functionsPart 3-functions
Part 3-functionsankita44
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2Warui Maina
 
fraction_math.c for Project 5 Program Design fraction.pdf
fraction_math.c for Project 5  Program Design  fraction.pdffraction_math.c for Project 5  Program Design  fraction.pdf
fraction_math.c for Project 5 Program Design fraction.pdfanjanadistribution
 
Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functionsTAlha MAlik
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Sheik Uduman Ali
 
Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01Abdul Samee
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxKhurramKhan173
 

Semelhante a Operator Overloading: Lecture 17 (20)

Lecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handlingLecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handling
 
#ifndef RATIONAL_H   if this compiler macro is not defined #def.pdf
#ifndef RATIONAL_H    if this compiler macro is not defined #def.pdf#ifndef RATIONAL_H    if this compiler macro is not defined #def.pdf
#ifndef RATIONAL_H   if this compiler macro is not defined #def.pdf
 
write the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdfwrite the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdf
 
C++ manual Report Full
C++ manual Report FullC++ manual Report Full
C++ manual Report Full
 
C++ aptitude
C++ aptitudeC++ aptitude
C++ aptitude
 
User defined functions
User defined functionsUser defined functions
User defined functions
 
Functions12
Functions12Functions12
Functions12
 
Functions123
Functions123 Functions123
Functions123
 
Operators1.pptx
Operators1.pptxOperators1.pptx
Operators1.pptx
 
PROGRAM 2 – Fraction Class Problem For this programming as.pdf
PROGRAM 2 – Fraction Class Problem For this programming as.pdfPROGRAM 2 – Fraction Class Problem For this programming as.pdf
PROGRAM 2 – Fraction Class Problem For this programming as.pdf
 
Function notes 2
Function notes 2Function notes 2
Function notes 2
 
Functions
FunctionsFunctions
Functions
 
AnswerNote Provided code shows several bugs, hence I implemented.pdf
AnswerNote Provided code shows several bugs, hence I implemented.pdfAnswerNote Provided code shows several bugs, hence I implemented.pdf
AnswerNote Provided code shows several bugs, hence I implemented.pdf
 
Part 3-functions
Part 3-functionsPart 3-functions
Part 3-functions
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
 
fraction_math.c for Project 5 Program Design fraction.pdf
fraction_math.c for Project 5  Program Design  fraction.pdffraction_math.c for Project 5  Program Design  fraction.pdf
fraction_math.c for Project 5 Program Design fraction.pdf
 
Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functions
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0
 
Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
 

Mais de elearning_portal (7)

Lecture19
Lecture19Lecture19
Lecture19
 
Lecture18
Lecture18Lecture18
Lecture18
 
Lecture06
Lecture06Lecture06
Lecture06
 
Lecture03
Lecture03Lecture03
Lecture03
 
Lecture02
Lecture02Lecture02
Lecture02
 
Lecture01
Lecture01Lecture01
Lecture01
 
Lecture04
Lecture04Lecture04
Lecture04
 

Último

Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsManeerUddin
 

Último (20)

Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture hons
 

Operator Overloading: Lecture 17

  • 2. Introduction A number of predefined operators can be applied to the built- in standard types. These operators can be overloaded, means each of them can be used for several standard types. For example: operator + operates on int, float and double. So + is already OverLoaded ( same interface but different implementations) Can + --- ADD A & B Adding additional processing power to the operator.2
  • 3. Introduction The operators that can be overloaded are + - * / % ^ & | ~ ! = < > += -= *= /= %= ^= &= |= << >> >>= <<= == != <= >= && || ++ -- ->* , -> [] () new delete new[] delete[] The operators that cannot be overloaded are . .* :: ?: sizeof 3
  • 4. Overloading the assignment operator (=) Purpose of assignment operator is to copy one object or value to another. Similar to the default constructor, the copy constructor, and the destructor, the assignment operator is created automatically for every class that is defined. But also the assignment operator can be defined explicitly in the class definition. How to overload operator? Write a function with the keyword operatorX, where X is an operator symbol. For example: operator= 4
  • 5. Sample program to overload assignment operator (1st. version) #include<iostream.h> void main() class Rational { { Rational x(22,7), z; public: x.print(); cout<<endl; Rational (int=0, int=1); z.print(); cout<<endl; void operator=(const Rational&); z = x; void print() { cout << num << '/’ << den x.print(); cout<<endl; << endl;} z.print(); cout<<endl; private: } //end main block int num; int den; Output: }; 22/7 Rational::Rational(int n, int d) 0/1 { num = n; 22/7 den = d; } // end Rational::Rational() 22/7 void Rational::operator=(const Rational& r) This version does not check for { num = r.num; den = r.den; self assignment (z=z) and allow } // end Rational::operator=() chained assignments (z = x = y). 5
  • 6. Sample program to overload assignment operator (1st. version) Rational::Rational(int n=0, int d=1) { num = n; z x den = d; } // end Rational::Rational() num = 0 num = 22 den = 1 den = 7 void Rational::operator=(const Rational& r) Rational x(22,7), z; { num = r.num; den = r.den; z = x; } // end Rational::operator=() 6
  • 7. Sample program to overload assignment operator (2nd. version) #include<iostream.h> Rational Rational::operator= (const Rational& r) class Rational { { num = r.num; public: den = r.den; Rational (int=0, int=1); return *this; }// end Rational::operator= Ratinal operator=(const Rational&); void print() { cout << num << '/’ << den void main() << endl;} { Rational x(22,7), y(-3,8), z; private: x.print(); cout<<endl; // prints 22/7 int num; y.print(); cout<<endl; // prints -3/8 int den; z.print(); cout<<endl; // prints 0/1 }; z = x = y; x.print(); cout<<endl; // prints -3/8 Rational::Rational(int n, int d) y.print(); cout<<endl; // prints -3/8 { num = n; z.print(); cout<<endl; // prints -3/8 den = d; }// end Rational::Rational } //end main block 7
  • 8. Sample program to overload assignment operator (1st. version) z x y num = 0 num = 22 num = -3 den = 1 den = 7 den = 8 void Rational::operator=(const Rational& r) Rational x(22,7), y(-3,8); z; { num = r.num; den = r.den; z = x = y; return *this; } // end Rational::operator=() 8
  • 9. Overloading the arithmetic operators (+, -, *, /) #include<iostream.h> void Rational::operator=(const Rational& r) class Rational { { num = r.num; den = r.den; friend Rational operator* (const Rational&, return this; const Rational&); } // end Rational::operator=() public: Rational (int=0, int=1); void main() Rational operator=(const Rational&); { Rational a(22,7), b(-3, 8), c; void print() { cout << num << '/’ << den c = a; << endl;} c.print(); cout<<endl; //prints 22/7 private: int num; c = a * b; int den; c.print(); cout<<endl; //prints -66/42 }; } //end main block Note: Rational operator*(const Rational& x, const •The operator* function is not a Rational& y) { Rational result; member function of class Rational but result.num = x.num * y.num; as a friend of the class Rational. result.den = x.den * y.den; •The operator* function requires two return result; } // end Rational operator*() arguments. 9
  • 10. Sample program to overload assignment operator (1st. version) c a b num = 0 num = 22 * num = -3 den = 1 den = 7 * den = 8 Rational operator*(const Rational& x, const Rational& y) Rational a(22,7), b(-3,8); c; { Rational result; result.num = x.num * y.num; result.den = x.den * y.den; c = a * b; return result; } // end Rational operator*() 10
  • 11. Overloading the arithmetic assignment operators (+=, -=, *=, /=) #include<iostream.h> void Rational::operator=(const Rational& r) class Rational { { num = r.num; public: den = r.den; Rational (int=0, int=1); return *this; Rational operator=(const Rational&); } // end Rational::operator=() Rational operator*=(const Rational&); void print() { cout << num << '/’ << den void main() << endl;} { Rational frac1(22,7), frac2(-3, 8), frac3; private: frac3 = frac1; int num; frac3.print(); cout<<endl; //prints 22/7 int den; frac1 *= frac2; }; frac1.print(); cout<<endl; //prints -66/42 } //end main block Rational Rational::operator*= (const Rational& x ) By returning *this, the operator can be { num = num * x.num; chained, like: x *= y *= z; den = den * x.den; return *this; } // end Rational::operator*=() 11