SlideShare a Scribd company logo
1 of 14
CSE240 – Introduction to
Programming Languages
Lecture 15:
Programming with C++ | Overloading
Javier Gonzalez-Sanchez
javiergs@asu.edu
javiergs.engineering.asu.edu
Office Hours: By appointment
Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 2
Function Overloading
• Multiple functions can have the same name, but different parameter list in
type or in number.
• Destructor cannot be overloaded, because it does not have parameter
void function(int v) {
// code
}
void function(double v) {
// code
}
Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 3
Overloaded Functions vs. Virtual Functions
• Multiple functions can have the same name, but different parameter list in
type or in number.
• Overloading can be applied to constructors and normal functions.
• Overloading does not allow functions to have the same parameter list but
different return type.
• Virtual functions in the base class and derived class must have the same
parameter list and return type.
Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 4
Overloaded Functions vs. Virtual Functions
• Multiple functions can have the same name, but different parameter list in
type or in number.
• Overloading can be applied to constructors and normal functions.
• Overloading does not allow functions to have the same parameter list but
different return type.
• Virtual functions in the base class and derived class must have the same
parameter list and return type.
void enqueue(int v) {
if (rear < queue_size) buffer[rear++] = v;
else if (compact()) buffer[rear++] = v;
}
void enqueue(double v) {
if (rear < queue_size) buffer[rear++] = v;
else if (compact()) buffer[rear++] = v;
}
virtual void display() {
// different implementations in different classes
}
Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 5
Operator Overloading in C++
Like function overloading, C++ allows user to define operator (built-in function)
overloading.
Why do we need operator overloading?
• string1 = string2; instead of using strcpy(string1, string2);
• string1 >= string2; instead of using strcmp(string1, string2);
• rectangleArea(3, 5) < rectangleArea(2, 6)
• time1(3, 23) + time2(5, 56), resulting in: time3(9, 19)
• Increament a Date(year, month, day) object, what is the next date?
Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 6
Example 1
int main() {
Cylinder cylinder1, cylinder2, cylinder3;
double volume = 0.0;
// cylinder1 and cylinder2 initialization
cylinder1.setRadius(5.0); cylinder1.setHeight(5.0);
cylinder2.setRadius(4.0); cylinder2.setHeight(10.0);
// get and print volumes of cylinder1 and cylinder2
volume = cylinder1.getVolume();
cout << "Volume of cylinder1 : " << volume << endl;
volume = cylinder2.getVolume();
cout << "Volume of cylinder2 : " << volume << endl;
// Add two objects using overloaded operator +, and get and print volume
cylinder3 = cylinder1 + cylinder2;
volume = cylinder3.getVolume();
cout << "Volume of cylinder3 : " << volume << endl;
// Subtract two object as follows:
cylinder3 = cylinder1 - cylinder2;
// get and print volume of cylinder 3
volume = cylinder3.getVolume();
cout << "Volume of cylinder3 : " << volume << endl;
if (cylinder1 > cylinder2) // using overloaded operator >
cout << "cylinder1 volume is greater than cylinder2 volume" << endl;
else cout << "cylinder1 volume is not greater than cylinder2 volume" << endl;
return 0;
}
Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 7
Example 1
#include <iostream>
#include <cmath>
using namespace std;
class Cylinder {
private:
double radius, height;
public:
double getVolume(void) {
// M_PI defined in <cmath>
return M_PI * radius * radius * height;
}
void setRadius(double r) {
radius = r;
}
void setHeight(int h) {
height = h;
}
radius
height
Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 8
Example 1
// Overload + operator to add two Cylinder objects.
Cylinder operator+(Cylinder &c) {
Cylinder cylinder;
cylinder.radius = this->radius + c.radius;
cylinder.height = this->height + c.height;
return cylinder;
}
// Overload - operator to subtract two Cylinder objects.
Cylinder operator-(Cylinder &c) {
Cylinder cylinder;
cylinder.radius = this->radius - c.radius;
cylinder.height = this->height - c.height;
return cylinder;
}
// Overload - operator > (greater than of two Cylinder objects).
bool operator>(Cylinder &c) {
Cylinder cylinder; double vol0, vol1;
vol0 = this->getVolume();
vol1 = c.getVolume();
if (vol0 > vol1) return true;
else return false;
} };
Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 9
int main() {
Days day1(Mon), day2, day3;
day2.setDay(Sat); day3.setDay(Sun);
cout << "The days before ++ operations" << endl;
day1.display(); day2.display(); day3.display();
++day1; ++day2; ++day3;
cout << "The days after prefix ++ operations" << endl;
day1.display(); day2.display();
day3.display();
day1++; day2++; day3++;
cout << "The days after postfix ++ operations" << endl;
day1.display(); day2.display(); day3.display();
return 0;
}
Example 2
Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 10
Example 2
#include <iostream>
using namespace std;
typedef enum { Sun = 0, Mon, Tue, Wed, Thu, Fri, Sat } DayType;
class Days {
private:
DayType day;
public:
Days() { day = Sun; } // constructor without parameter
Days(DayType d) { day = d; } // constructor with a parameter
DayType getDay(void) { return day; }
void setDay(DayType d) { if (d >= Sun && d <= Sat) this->day = d;}
void display() {
switch (day) { case Sun: cout << "Sun" << endl; break;
case Mon: cout << "Mon" << endl; break;
case Tue: cout << "Tue" << endl; break;
case Wed: cout << "Wed" << endl; break;
case Thu: cout << "Thu" << endl; break;
case Fri: cout << "Fri" << endl; break;
case Sat: cout << "Sat" << endl; break;
default: cout << "Incorrect day" << endl; } }
Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 11
Example 2
// Overload prefix ++ operator to add one to Days object: ++days.
Days operator++() {
Days days(day); // Save the original value
switch (this->day) {
case Sun: this->day = Mon; break;
case Mon: this->day = Tue; break;
case Tue: this->day = Wed; break;
case Wed: this->day = Thu; break;
case Thu: this->day = Fri; break;
case Fri: this->day = Sat; break;
case Sat: this->day = Sun; break;
default: cout << "Incorrect day" << endl;
}
days.day = this->day;
return days;
}
Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 12
Example 2
// Overload postfix ++ operator to add one to Days object: days++.
Days operator++(int) { // This parameter indicates ++ follows a parameter
Days days(day); // Save the original value
switch (this->day) {
case Sun: this->day = Mon; break;
case Mon: this->day = Tue; break;
case Tue: this->day = Wed; break;
case Wed: this->day = Thu; break;
case Thu: this->day = Fri; break;
case Fri: this->day = Sat; break;
case Sat: this->day = Sun; break;
default: cout << "Incorrect day" << endl;
} // The value in the this object has been changed.
// days.day = this->day;
return days; // return the value before the changes.
}
};
Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 13
Operator Overloading
• can be
overloaded
• Cannot be
overloaded
+ - * / % ^
& | ~ ! , =
< > <= >= ++ --
<< >> == != && ||
+= -= /= %= ^= &=
|= *= <<= >>= [] ()
-> ->* new new [] delete delete []
:: .* . ?:
CSE240 – Introduction to Programming Languages
Javier Gonzalez-Sanchez
javiergs@asu.edu
Fall 2017
Disclaimer. These slides can only be used as study material for the class CSE240 at ASU. They cannot be distributed or used for another purpose.

More Related Content

What's hot

No More, No Less: A Formal Model for Serverless Computing
No More, No Less: A Formal Model for Serverless ComputingNo More, No Less: A Formal Model for Serverless Computing
No More, No Less: A Formal Model for Serverless ComputingMarco Peressotti
 
Program pengurutan data
Program pengurutan dataProgram pengurutan data
Program pengurutan datalinda_rosalina
 
Dynamically Evolving Systems: Cluster Analysis Using Time
Dynamically Evolving Systems: Cluster Analysis Using TimeDynamically Evolving Systems: Cluster Analysis Using Time
Dynamically Evolving Systems: Cluster Analysis Using TimeMagnify Analytic Solutions
 
How the Go runtime implement maps efficiently
How the Go runtime implement maps efficientlyHow the Go runtime implement maps efficiently
How the Go runtime implement maps efficientlyTing-Li Chou
 
Kapacitor Alert Topic handlers
Kapacitor Alert Topic handlersKapacitor Alert Topic handlers
Kapacitor Alert Topic handlersInfluxData
 
Script PyThon
Script PyThonScript PyThon
Script PyThoninacap
 
Real World Optimization
Real World OptimizationReal World Optimization
Real World OptimizationDavid Golden
 
Probability of finding a single qubit in a state
Probability of finding a single qubit in a stateProbability of finding a single qubit in a state
Probability of finding a single qubit in a stateVijayananda Mohire
 
Scott Anderson [InfluxData] | InfluxDB Tasks – Beyond Downsampling | InfluxDa...
Scott Anderson [InfluxData] | InfluxDB Tasks – Beyond Downsampling | InfluxDa...Scott Anderson [InfluxData] | InfluxDB Tasks – Beyond Downsampling | InfluxDa...
Scott Anderson [InfluxData] | InfluxDB Tasks – Beyond Downsampling | InfluxDa...InfluxData
 
The Ring programming language version 1.5.4 book - Part 62 of 185
The Ring programming language version 1.5.4 book - Part 62 of 185The Ring programming language version 1.5.4 book - Part 62 of 185
The Ring programming language version 1.5.4 book - Part 62 of 185Mahmoud Samir Fayed
 
The Ring programming language version 1.9 book - Part 75 of 210
The Ring programming language version 1.9 book - Part 75 of 210The Ring programming language version 1.9 book - Part 75 of 210
The Ring programming language version 1.9 book - Part 75 of 210Mahmoud Samir Fayed
 
Probabilistic data structures. Part 2. Cardinality
Probabilistic data structures. Part 2. CardinalityProbabilistic data structures. Part 2. Cardinality
Probabilistic data structures. Part 2. CardinalityAndrii Gakhov
 
Regular expressions, Alex Perry, Google, PyCon2014
Regular expressions, Alex Perry, Google, PyCon2014Regular expressions, Alex Perry, Google, PyCon2014
Regular expressions, Alex Perry, Google, PyCon2014alex_perry
 
Standing the Test of Time: The Date Provider Pattern
Standing the Test of Time: The Date Provider PatternStanding the Test of Time: The Date Provider Pattern
Standing the Test of Time: The Date Provider PatternDerek Lee Boire
 

What's hot (17)

No More, No Less: A Formal Model for Serverless Computing
No More, No Less: A Formal Model for Serverless ComputingNo More, No Less: A Formal Model for Serverless Computing
No More, No Less: A Formal Model for Serverless Computing
 
Program pengurutan data
Program pengurutan dataProgram pengurutan data
Program pengurutan data
 
R and C++
R and C++R and C++
R and C++
 
Dynamically Evolving Systems: Cluster Analysis Using Time
Dynamically Evolving Systems: Cluster Analysis Using TimeDynamically Evolving Systems: Cluster Analysis Using Time
Dynamically Evolving Systems: Cluster Analysis Using Time
 
How the Go runtime implement maps efficiently
How the Go runtime implement maps efficientlyHow the Go runtime implement maps efficiently
How the Go runtime implement maps efficiently
 
Kapacitor Alert Topic handlers
Kapacitor Alert Topic handlersKapacitor Alert Topic handlers
Kapacitor Alert Topic handlers
 
Multi qubit entanglement
Multi qubit entanglementMulti qubit entanglement
Multi qubit entanglement
 
Script PyThon
Script PyThonScript PyThon
Script PyThon
 
Real World Optimization
Real World OptimizationReal World Optimization
Real World Optimization
 
F
FF
F
 
Probability of finding a single qubit in a state
Probability of finding a single qubit in a stateProbability of finding a single qubit in a state
Probability of finding a single qubit in a state
 
Scott Anderson [InfluxData] | InfluxDB Tasks – Beyond Downsampling | InfluxDa...
Scott Anderson [InfluxData] | InfluxDB Tasks – Beyond Downsampling | InfluxDa...Scott Anderson [InfluxData] | InfluxDB Tasks – Beyond Downsampling | InfluxDa...
Scott Anderson [InfluxData] | InfluxDB Tasks – Beyond Downsampling | InfluxDa...
 
The Ring programming language version 1.5.4 book - Part 62 of 185
The Ring programming language version 1.5.4 book - Part 62 of 185The Ring programming language version 1.5.4 book - Part 62 of 185
The Ring programming language version 1.5.4 book - Part 62 of 185
 
The Ring programming language version 1.9 book - Part 75 of 210
The Ring programming language version 1.9 book - Part 75 of 210The Ring programming language version 1.9 book - Part 75 of 210
The Ring programming language version 1.9 book - Part 75 of 210
 
Probabilistic data structures. Part 2. Cardinality
Probabilistic data structures. Part 2. CardinalityProbabilistic data structures. Part 2. Cardinality
Probabilistic data structures. Part 2. Cardinality
 
Regular expressions, Alex Perry, Google, PyCon2014
Regular expressions, Alex Perry, Google, PyCon2014Regular expressions, Alex Perry, Google, PyCon2014
Regular expressions, Alex Perry, Google, PyCon2014
 
Standing the Test of Time: The Date Provider Pattern
Standing the Test of Time: The Date Provider PatternStanding the Test of Time: The Date Provider Pattern
Standing the Test of Time: The Date Provider Pattern
 

Similar to C++ Function and Operator Overloading

Problem Solving Techniques For Evolutionary Design
Problem Solving Techniques For Evolutionary DesignProblem Solving Techniques For Evolutionary Design
Problem Solving Techniques For Evolutionary DesignNaresh Jain
 
C++ Please I am posting the fifth time and hoping to get th.pdf
C++ Please I am posting the fifth time and hoping to get th.pdfC++ Please I am posting the fifth time and hoping to get th.pdf
C++ Please I am posting the fifth time and hoping to get th.pdfjaipur2
 
Implement a function in c++ which takes in a vector of integers and .pdf
Implement a function in c++ which takes in a vector of integers and .pdfImplement a function in c++ which takes in a vector of integers and .pdf
Implement a function in c++ which takes in a vector of integers and .pdffeelingspaldi
 
Modify the Date class that was covered in the lecture which overload.pdf
Modify the Date class that was covered in the lecture which overload.pdfModify the Date class that was covered in the lecture which overload.pdf
Modify the Date class that was covered in the lecture which overload.pdfsaxenaavnish1
 
JAVA.Q4 Create a Time class. This class will represent a point in.pdf
JAVA.Q4 Create a Time class. This class will represent a point in.pdfJAVA.Q4 Create a Time class. This class will represent a point in.pdf
JAVA.Q4 Create a Time class. This class will represent a point in.pdfkarymadelaneyrenne19
 
Please I am posting the fifth time and hoping to get this r.pdf
Please I am posting the fifth time and hoping to get this r.pdfPlease I am posting the fifth time and hoping to get this r.pdf
Please I am posting the fifth time and hoping to get this r.pdfankit11134
 
Architecture for scalable Angular applications
Architecture for scalable Angular applicationsArchitecture for scalable Angular applications
Architecture for scalable Angular applicationsPaweł Żurowski
 
4Developers 2018: Beyond c++17 (Mateusz Pusz)
4Developers 2018: Beyond c++17 (Mateusz Pusz)4Developers 2018: Beyond c++17 (Mateusz Pusz)
4Developers 2018: Beyond c++17 (Mateusz Pusz)PROIDEA
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2zindadili
 
C++ process new
C++ process newC++ process new
C++ process new敬倫 林
 
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloadingkinan keshkeh
 

Similar to C++ Function and Operator Overloading (20)

Problem Solving Techniques For Evolutionary Design
Problem Solving Techniques For Evolutionary DesignProblem Solving Techniques For Evolutionary Design
Problem Solving Techniques For Evolutionary Design
 
Refactoring
RefactoringRefactoring
Refactoring
 
lecture56.ppt
lecture56.pptlecture56.ppt
lecture56.ppt
 
Functional C++
Functional C++Functional C++
Functional C++
 
Week7a.pptx
Week7a.pptxWeek7a.pptx
Week7a.pptx
 
PVS-Studio in 2019
PVS-Studio in 2019PVS-Studio in 2019
PVS-Studio in 2019
 
C++ Please I am posting the fifth time and hoping to get th.pdf
C++ Please I am posting the fifth time and hoping to get th.pdfC++ Please I am posting the fifth time and hoping to get th.pdf
C++ Please I am posting the fifth time and hoping to get th.pdf
 
Implement a function in c++ which takes in a vector of integers and .pdf
Implement a function in c++ which takes in a vector of integers and .pdfImplement a function in c++ which takes in a vector of integers and .pdf
Implement a function in c++ which takes in a vector of integers and .pdf
 
Modify the Date class that was covered in the lecture which overload.pdf
Modify the Date class that was covered in the lecture which overload.pdfModify the Date class that was covered in the lecture which overload.pdf
Modify the Date class that was covered in the lecture which overload.pdf
 
JAVA.Q4 Create a Time class. This class will represent a point in.pdf
JAVA.Q4 Create a Time class. This class will represent a point in.pdfJAVA.Q4 Create a Time class. This class will represent a point in.pdf
JAVA.Q4 Create a Time class. This class will represent a point in.pdf
 
Please I am posting the fifth time and hoping to get this r.pdf
Please I am posting the fifth time and hoping to get this r.pdfPlease I am posting the fifth time and hoping to get this r.pdf
Please I am posting the fifth time and hoping to get this r.pdf
 
ThreeTen
ThreeTenThreeTen
ThreeTen
 
Architecture for scalable Angular applications
Architecture for scalable Angular applicationsArchitecture for scalable Angular applications
Architecture for scalable Angular applications
 
4Developers 2018: Beyond c++17 (Mateusz Pusz)
4Developers 2018: Beyond c++17 (Mateusz Pusz)4Developers 2018: Beyond c++17 (Mateusz Pusz)
4Developers 2018: Beyond c++17 (Mateusz Pusz)
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
 
C++ process new
C++ process newC++ process new
C++ process new
 
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
 
Jsr310
Jsr310Jsr310
Jsr310
 
Apclass
ApclassApclass
Apclass
 

More from Javier Gonzalez-Sanchez (20)

201804 SER332 Lecture 01
201804 SER332 Lecture 01201804 SER332 Lecture 01
201804 SER332 Lecture 01
 
201801 SER332 Lecture 03
201801 SER332 Lecture 03201801 SER332 Lecture 03
201801 SER332 Lecture 03
 
201801 SER332 Lecture 04
201801 SER332 Lecture 04201801 SER332 Lecture 04
201801 SER332 Lecture 04
 
201801 SER332 Lecture 02
201801 SER332 Lecture 02201801 SER332 Lecture 02
201801 SER332 Lecture 02
 
201801 CSE240 Lecture 26
201801 CSE240 Lecture 26201801 CSE240 Lecture 26
201801 CSE240 Lecture 26
 
201801 CSE240 Lecture 25
201801 CSE240 Lecture 25201801 CSE240 Lecture 25
201801 CSE240 Lecture 25
 
201801 CSE240 Lecture 24
201801 CSE240 Lecture 24201801 CSE240 Lecture 24
201801 CSE240 Lecture 24
 
201801 CSE240 Lecture 23
201801 CSE240 Lecture 23201801 CSE240 Lecture 23
201801 CSE240 Lecture 23
 
201801 CSE240 Lecture 22
201801 CSE240 Lecture 22201801 CSE240 Lecture 22
201801 CSE240 Lecture 22
 
201801 CSE240 Lecture 21
201801 CSE240 Lecture 21201801 CSE240 Lecture 21
201801 CSE240 Lecture 21
 
201801 CSE240 Lecture 20
201801 CSE240 Lecture 20201801 CSE240 Lecture 20
201801 CSE240 Lecture 20
 
201801 CSE240 Lecture 19
201801 CSE240 Lecture 19201801 CSE240 Lecture 19
201801 CSE240 Lecture 19
 
201801 CSE240 Lecture 18
201801 CSE240 Lecture 18201801 CSE240 Lecture 18
201801 CSE240 Lecture 18
 
201801 CSE240 Lecture 17
201801 CSE240 Lecture 17201801 CSE240 Lecture 17
201801 CSE240 Lecture 17
 
201801 CSE240 Lecture 16
201801 CSE240 Lecture 16201801 CSE240 Lecture 16
201801 CSE240 Lecture 16
 
201801 CSE240 Lecture 14
201801 CSE240 Lecture 14201801 CSE240 Lecture 14
201801 CSE240 Lecture 14
 
201801 CSE240 Lecture 13
201801 CSE240 Lecture 13201801 CSE240 Lecture 13
201801 CSE240 Lecture 13
 
201801 CSE240 Lecture 11
201801 CSE240 Lecture 11201801 CSE240 Lecture 11
201801 CSE240 Lecture 11
 
201801 CSE240 Lecture 10
201801 CSE240 Lecture 10201801 CSE240 Lecture 10
201801 CSE240 Lecture 10
 
201801 CSE240 Lecture 09
201801 CSE240 Lecture 09201801 CSE240 Lecture 09
201801 CSE240 Lecture 09
 

Recently uploaded

Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 

Recently uploaded (20)

Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 

C++ Function and Operator Overloading

  • 1. CSE240 – Introduction to Programming Languages Lecture 15: Programming with C++ | Overloading Javier Gonzalez-Sanchez javiergs@asu.edu javiergs.engineering.asu.edu Office Hours: By appointment
  • 2. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 2 Function Overloading • Multiple functions can have the same name, but different parameter list in type or in number. • Destructor cannot be overloaded, because it does not have parameter void function(int v) { // code } void function(double v) { // code }
  • 3. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 3 Overloaded Functions vs. Virtual Functions • Multiple functions can have the same name, but different parameter list in type or in number. • Overloading can be applied to constructors and normal functions. • Overloading does not allow functions to have the same parameter list but different return type. • Virtual functions in the base class and derived class must have the same parameter list and return type.
  • 4. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 4 Overloaded Functions vs. Virtual Functions • Multiple functions can have the same name, but different parameter list in type or in number. • Overloading can be applied to constructors and normal functions. • Overloading does not allow functions to have the same parameter list but different return type. • Virtual functions in the base class and derived class must have the same parameter list and return type. void enqueue(int v) { if (rear < queue_size) buffer[rear++] = v; else if (compact()) buffer[rear++] = v; } void enqueue(double v) { if (rear < queue_size) buffer[rear++] = v; else if (compact()) buffer[rear++] = v; } virtual void display() { // different implementations in different classes }
  • 5. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 5 Operator Overloading in C++ Like function overloading, C++ allows user to define operator (built-in function) overloading. Why do we need operator overloading? • string1 = string2; instead of using strcpy(string1, string2); • string1 >= string2; instead of using strcmp(string1, string2); • rectangleArea(3, 5) < rectangleArea(2, 6) • time1(3, 23) + time2(5, 56), resulting in: time3(9, 19) • Increament a Date(year, month, day) object, what is the next date?
  • 6. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 6 Example 1 int main() { Cylinder cylinder1, cylinder2, cylinder3; double volume = 0.0; // cylinder1 and cylinder2 initialization cylinder1.setRadius(5.0); cylinder1.setHeight(5.0); cylinder2.setRadius(4.0); cylinder2.setHeight(10.0); // get and print volumes of cylinder1 and cylinder2 volume = cylinder1.getVolume(); cout << "Volume of cylinder1 : " << volume << endl; volume = cylinder2.getVolume(); cout << "Volume of cylinder2 : " << volume << endl; // Add two objects using overloaded operator +, and get and print volume cylinder3 = cylinder1 + cylinder2; volume = cylinder3.getVolume(); cout << "Volume of cylinder3 : " << volume << endl; // Subtract two object as follows: cylinder3 = cylinder1 - cylinder2; // get and print volume of cylinder 3 volume = cylinder3.getVolume(); cout << "Volume of cylinder3 : " << volume << endl; if (cylinder1 > cylinder2) // using overloaded operator > cout << "cylinder1 volume is greater than cylinder2 volume" << endl; else cout << "cylinder1 volume is not greater than cylinder2 volume" << endl; return 0; }
  • 7. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 7 Example 1 #include <iostream> #include <cmath> using namespace std; class Cylinder { private: double radius, height; public: double getVolume(void) { // M_PI defined in <cmath> return M_PI * radius * radius * height; } void setRadius(double r) { radius = r; } void setHeight(int h) { height = h; } radius height
  • 8. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 8 Example 1 // Overload + operator to add two Cylinder objects. Cylinder operator+(Cylinder &c) { Cylinder cylinder; cylinder.radius = this->radius + c.radius; cylinder.height = this->height + c.height; return cylinder; } // Overload - operator to subtract two Cylinder objects. Cylinder operator-(Cylinder &c) { Cylinder cylinder; cylinder.radius = this->radius - c.radius; cylinder.height = this->height - c.height; return cylinder; } // Overload - operator > (greater than of two Cylinder objects). bool operator>(Cylinder &c) { Cylinder cylinder; double vol0, vol1; vol0 = this->getVolume(); vol1 = c.getVolume(); if (vol0 > vol1) return true; else return false; } };
  • 9. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 9 int main() { Days day1(Mon), day2, day3; day2.setDay(Sat); day3.setDay(Sun); cout << "The days before ++ operations" << endl; day1.display(); day2.display(); day3.display(); ++day1; ++day2; ++day3; cout << "The days after prefix ++ operations" << endl; day1.display(); day2.display(); day3.display(); day1++; day2++; day3++; cout << "The days after postfix ++ operations" << endl; day1.display(); day2.display(); day3.display(); return 0; } Example 2
  • 10. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 10 Example 2 #include <iostream> using namespace std; typedef enum { Sun = 0, Mon, Tue, Wed, Thu, Fri, Sat } DayType; class Days { private: DayType day; public: Days() { day = Sun; } // constructor without parameter Days(DayType d) { day = d; } // constructor with a parameter DayType getDay(void) { return day; } void setDay(DayType d) { if (d >= Sun && d <= Sat) this->day = d;} void display() { switch (day) { case Sun: cout << "Sun" << endl; break; case Mon: cout << "Mon" << endl; break; case Tue: cout << "Tue" << endl; break; case Wed: cout << "Wed" << endl; break; case Thu: cout << "Thu" << endl; break; case Fri: cout << "Fri" << endl; break; case Sat: cout << "Sat" << endl; break; default: cout << "Incorrect day" << endl; } }
  • 11. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 11 Example 2 // Overload prefix ++ operator to add one to Days object: ++days. Days operator++() { Days days(day); // Save the original value switch (this->day) { case Sun: this->day = Mon; break; case Mon: this->day = Tue; break; case Tue: this->day = Wed; break; case Wed: this->day = Thu; break; case Thu: this->day = Fri; break; case Fri: this->day = Sat; break; case Sat: this->day = Sun; break; default: cout << "Incorrect day" << endl; } days.day = this->day; return days; }
  • 12. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 12 Example 2 // Overload postfix ++ operator to add one to Days object: days++. Days operator++(int) { // This parameter indicates ++ follows a parameter Days days(day); // Save the original value switch (this->day) { case Sun: this->day = Mon; break; case Mon: this->day = Tue; break; case Tue: this->day = Wed; break; case Wed: this->day = Thu; break; case Thu: this->day = Fri; break; case Fri: this->day = Sat; break; case Sat: this->day = Sun; break; default: cout << "Incorrect day" << endl; } // The value in the this object has been changed. // days.day = this->day; return days; // return the value before the changes. } };
  • 13. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 13 Operator Overloading • can be overloaded • Cannot be overloaded + - * / % ^ & | ~ ! , = < > <= >= ++ -- << >> == != && || += -= /= %= ^= &= |= *= <<= >>= [] () -> ->* new new [] delete delete [] :: .* . ?:
  • 14. CSE240 – Introduction to Programming Languages Javier Gonzalez-Sanchez javiergs@asu.edu Fall 2017 Disclaimer. These slides can only be used as study material for the class CSE240 at ASU. They cannot be distributed or used for another purpose.