SlideShare a Scribd company logo
1 of 29
+ - * / % & !
= ^ < > << >>
? | += -= *= /=
%= != &= >=
<= && || ++ -
-
. i.e. to overload an operator is to provide it a new meaning for
user defined data types.
In simple words we can say that by using Operator Overloading we can perform
basic operations like (Addition, Subtraction, multiplication, Division and so
on………..) on our own defined objects of the class
By Overloading the appropriate Operators, you can use Objects in
expressions in just the same way that you use built in data types in C++
Operator overloading allows full integration of new data types into the
programming environment because operators can be extended to work not just
with built-in data types but also with classes.
Operator Overloading is One of the most exciting feature
of Object oriented programming.
In C++ the Overloading principle applies not only to function
but to operators as well.
O
P
E
R
A
T
O
R
O
V
E
R
L
O
A
D
I
N
G
Explanation
Normally a=b+c ;
works only with basic data types such as int
and float, and attempting to apply it when a
b and c are objects of primitive data types.
However we can make this statement legal
even when a b and c are user defined
data_types.
And actually oprator_overloading
is the only feature that gives you
opportunity to redefine the C++
Language.
Unary
operators
!
-
++
--
An Example that will illustrate how to overload unary
operators:
//Increment counter variable with ++ Operator
//////////////////////////////////////////////////////////////////////////////////////
#include<iostream.h>
#include<conio.h>
Class counter
{
private:
int count; //count
public:
counter() : count(0) //constructor
{ }
int get_count() //return count
Void operator ++() //increment (prefix)
{
++count;
}
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
void main()
{
counter c1, c2; //define and initialize
cout<<“n c1=“<<c1.get_count(); //display
cout<<“n c2=“<<c2.get_count();
++c1; //increment c1
++c2; //increment c2
++c2; //increment c2
cout<<“n c1=“<<c1.get_count(); //display again
cout<<“n c2=“<<c2.get_count() <<endl;
getch();
} // - - - -- end of program - - - - - -- //
Here is the program’s output:
C1=0 counts are initially 0
C2=0
C1=1 incremented once
C2=2 incremented twice
OPERATOR ARGUMENTS
In main () the ++ operator is applied to a specific object, as in
the expression ++c1. Yet
operator++() takes no arguments. What does this operator
increment? It increments the Count data in the object of
which it is a member. Since member functions can always
access
the particular object for which they’ve been invoked, this
operator requires no arguments.
Binary Operators can be overloaded just
as easily as Unary operators, we
frequently use binary operators to
perform various arithmetic operations,
but by overloading binary operators we
are able to perform various arithmetic
operations on our own user-defined data
types.
Binary
Arithmetic
Operators
Relational
Operators
Logical
Operators
OVERLOADING ARITHMETIC OPERATOR
Some of the most commonly used operators in C++ are
the arithmetic operators i.e. addition operator (+),
subtraction operator (-), multiplication operator (*) and
division operator(/).
All the Arithmetic operators are Binary operators and
binary operators and binary operators are overloaded in
exactly the same way as the unary operators.
Binary operators operate on two operands. i.e. One from
each side of the operator.
For example: a + b, a – b, a * b, a / b.
Here is a program that will show you how to
overload arithmetic operator.
// overloaded ‘+’ operator adds two Distances
#include <iostream.h>
class Distance //English Distance class
{
private:
int feet;
float inches;
public: //constructor (no args)
Distance() : feet(0), inches(0.0)
{ } //constructor (two args)
Distance(int ft, float in) : feet(ft), inches(in)
{ }
void getdist() //get length from user
{
cout << “nEnter feet: “; cin >> feet;
cout << “Enter inches: “; cin >> inches;
}
void showdist() const //display distance
{ cout << feet << “’-” << inches << ‘”’; }
Distance operator + ( Distance ) const; //add 2 distances
};
Distance Distance::operator + (Distance d2) const //return sum
{
int f = feet + d2.feet; //add the feet
float i = inches + d2.inches; //add the inches
if(i >= 12.0) //if total exceeds 12.0,
{ //then decrease inches
i -= 12.0; //by 12.0 and
f++; //increase feet by 1
} //return a temporary Distance
return Distance(f,i); //initialized to sum
}
int main()
{
Distance dist1, dist3, dist4; //define distances
dist1.getdist(); //get dist1 from user
Distance dist2(11, 6.25); //define, initialize dist2
dist3 = dist1 + dist2; //single ‘+’ operator
dist4 = dist1 + dist2 + dist3; //multiple ‘+’ operators
//display all lengths
cout << “dist1 = “; dist1.showdist(); cout << endl;
cout << “dist2 = “; dist2.showdist(); cout << endl;
cout << “dist3 = “; dist3.showdist(); cout << endl;
cout << “dist4 = “; dist4.showdist(); cout << endl;
return 0;
}
Explanation
To show that the result of an addition can be used in another
addition as well as in an assignment,
another addition is performed in main(). We add dist1, dist2, and
dist3 to obtain dist4
(which should be double the value of dist3), in the statement dist4
= dist1 + dist2 + dist3;
Here’s the output from the program:
Enter feet: 10
Enter inches: 6.5
dist1 = 10’-6.5” ← from user
dist2 = 11’-6.25” ← initialized in program
dist3 = 22’-0.75” ← dist1+dist2
dist4 = 44’-1.5” ← dist1+dist2+dist3
OVERLOADING RELATIONAL OPERATORS
There are various relational operators in C++ like (< ,>, <=, >=, == ,
etc.) these operators can be used to compare C++ built-in data types.
Any of these operators can be overloaded, which can be used to
compare the objects of a class.
Following EXAMPLE explains how a < operator can be overloaded,
and in the same way we are able to overload the other relational
operators.
All relational operators are binary, and should return either true or
false. Generally, all six operators can be based off a comparison
function, or each other, although this is never done automatically (e.g.
overloading > will not automatically overload < to give the opposite).
#include<iostream.h>
Class Distance
{
private:
int feet;
int inches;
public:
Distance() { feet=0; inches=0;}
Distance(int f, int i)
{ feet = f; inches=i; }
Void displayDistance ()
{
cout<<“F: “<<feet<<“I:”<<inches<<endl;
}
Distance operator - ()
{
feet=-feet;
inches=-inches;
return Distance(feet, inches);
}
bool operator < (const Distance & d)
{
if(feet<d.feet)
{return true; }
if(feet==d.feet && inches < d.inches)
{return true;}
Return false;
}
}; ////////////////////////////////////////////////////////////////////////////////////////////////////
ARITHMETIC ASSIGNMENT OPERATORS
Arithmetic Assignment operators are overloaded in exactly the
same way as we have overloaded all other arithmetic operators
and these operators can be used to create an object just like
copy constructors.
The following example explains how to overload an arithmetic
operator.
``````````````````````````````````````````````````````````````````````````````````
// overload ‘+=‘ assignment operator
#include<iostream.h>
class Distance //English Distance class
{
private:
int feet;
float inches;
public: //constructor (no args)
Distance() : feet(0), inches(0.0)
{ } //constructor (two args)
Distance(int ft, float in) : feet(ft), inches(in)
{ }
//--------------------------------------------------------------
//add distance to this one
void Distance::operator += (Distance d2)
{
feet += d2.feet; //add the feet
inches += d2.inches; //add the inches
if(inches >= 12.0) //if total exceeds 12.0,
{ //then decrease inches
inches -= 12.0; //by 12.0 and
feet++; //increase feet
} //by 1
}
////////////////////////////////////////////////////////////////
void getdist( ) //get length from user
{
cout << “nEnter feet: “; cin >> feet;
cout << “Enter inches: “; cin >> inches;
}
void showdist() const //display distance
{ cout << feet << “’-” << inches << ‘”’; }
void operator += ( Distance );
};
int main()
{
Distance dist1; //define dist1
dist1.getdist(); //get dist1 from user
cout << “ndist1 = “; dist1.showdist();
Distance dist2(11, 6.25); //define, initialize dist2
cout << “ndist2 = “; dist2.showdist();
dist1 += dist2; //dist1 = dist1 + dist2
cout << “n After addition,”;
cout << “ndist1 = “; dist1.showdist();
cout << endl;
return 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
The Operator Keyword
Sometimes question arises, How a normal C++ operator act
on a user-defined operand?
The Operator keyword is used to overload the ++ operator in
this declarator.
e.g. void operator ++().
Where void is the return type, the operator keyword is the
name of a function and the operator ++().
This declarator syntax tells the compiler to call this member
function, whenever the ++ operator is encountered.
If the operand is a basic type such as int as in ++ intvar, then
compiler use it’s built in routine to increment as int.
The compiler will know to use user-written operator ++()
instead.
NAMELESS TEMPORARY OBJECTS
Here’s the example:
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
class Counter
{
private:
unsigned int count; //count
public:
Counter() : count(0) //constructor no args
{ }
Counter(int c) : count(c) //constructor, one arg
{ }
unsigned int get_count() //return count
{ return count; }
Counter operator ++ () //increment count
{
++count; // increment count, then return
return Counter(count); // an unnamed temporary object
} // initialized to this count
};
////////////////////////////////////////////////////////////////
int main()
{
Counter c1, c2; //c1=0, c2=0
cout << “nc1=” << c1.get_count(); //display
cout << “nc2=” << c2.get_count();
++c1; //c1=1
c2 = ++c1; //c1=2, c2=2
cout << “nc1=” << c1.get_count(); //display again
cout << “nc2=” << c2.get_count() << endl;
return 0;
}
POSTFIX NOTATION
// postfix.cpp
// overloaded ++ operator in both prefix and postfix
#include <iostream.h>
class Counter
{
private:
unsigned int count; //count
public:
Counter() : count(0) //constructor no args
{ }
Counter(int c) : count(c) //constructor, one arg
{ }
unsigned int get_count() const //return count
{ return count; }
{ //increment count, then return
return Counter(++count); //an unnamed temporary object
} //initialized to this count
Counter operator ++ (int) //increment count (postfix)
{ //return an unnamed temporary
return Counter(count++); //object initialized to this
} //count, then increment count
};
////////////////////////////////////////////////////////////////
int main()
{
Counter c1, c2; //c1=0, c2=0
cout << “nc1=” << c1.get_count(); //display
cout << “nc2=” << c2.get_count();
++c1; //c1=1
c2 = ++c1; //c1=2, c2=2 (prefix)
cout << “nc1=” << c1.get_count(); //display
cout << “nc2=” << c2.get_count();
c2 = c1++; //c1=3, c2=2 (postfix)
cout << “nc1=” << c1.get_count(); //display again
cout << “nc2=” << c2.get_count() << endl;
return 0;
}
Counter operator ++ () //increment count (prefix)
Restrictions On Operator Overloading
There are Some Restrictions that apply to operator overloading,
for example we can not alter the precedence of an operator.
We cannot change the number of operands, that an operator
takes.
Operator function can not have default arguments.
No new operators can be created.
Finally the following operators ca not be overloaded:
. :: .* ?
operator overloading
operator overloading

More Related Content

What's hot

Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloadingPrincess Sam
 
operator overloading
operator overloadingoperator overloading
operator overloadingNishant Joshi
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingKumar
 
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator Overloading#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator OverloadingHadziq Fabroyir
 
OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++Aabha Tiwari
 
Bca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloadingBca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloadingRai University
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingKamal Acharya
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++gourav kottawar
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator OverloadingDustin Chase
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingArunaDevi63
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingabhay singh
 
Presentation on overloading
Presentation on overloading Presentation on overloading
Presentation on overloading Charndeep Sekhon
 
Operator overloadng
Operator overloadngOperator overloadng
Operator overloadngpreethalal
 
Operator Overloading & Type Conversions
Operator Overloading & Type ConversionsOperator Overloading & Type Conversions
Operator Overloading & Type ConversionsRokonuzzaman Rony
 

What's hot (20)

Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloading
 
operator overloading
operator overloadingoperator overloading
operator overloading
 
Lecture5
Lecture5Lecture5
Lecture5
 
Overloading
OverloadingOverloading
Overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator Overloading#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
 
OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++
 
Bca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloadingBca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
operator overloading in C++
operator overloading in C++operator overloading in C++
operator overloading in C++
 
Presentation on overloading
Presentation on overloading Presentation on overloading
Presentation on overloading
 
Operator overloadng
Operator overloadngOperator overloadng
Operator overloadng
 
Operator Overloading & Type Conversions
Operator Overloading & Type ConversionsOperator Overloading & Type Conversions
Operator Overloading & Type Conversions
 

Viewers also liked

Viewers also liked (6)

Function overloading
Function overloadingFunction overloading
Function overloading
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Operator overloading in C++
Operator overloading in C++Operator overloading in C++
Operator overloading in C++
 
Function Overlaoding
Function OverlaodingFunction Overlaoding
Function Overlaoding
 
06. operator overloading
06. operator overloading06. operator overloading
06. operator overloading
 
Function overloading
Function overloadingFunction overloading
Function overloading
 

Similar to operator overloading

Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2zindadili
 
Mca 2nd sem u-4 operator overloading
Mca 2nd  sem u-4 operator overloadingMca 2nd  sem u-4 operator overloading
Mca 2nd sem u-4 operator overloadingRai University
 
Ch-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdfCh-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdfesuEthopi
 
Cs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALCs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALPrabhu D
 
power point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions conceptspower point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions conceptsbhargavi804095
 
Functions in C++ programming language.pptx
Functions in  C++ programming language.pptxFunctions in  C++ programming language.pptx
Functions in C++ programming language.pptxrebin5725
 
#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
 
Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloadingPrincess Sam
 
overloading in C++
overloading in C++overloading in C++
overloading in C++Prof Ansari
 

Similar to operator overloading (20)

Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
 
Mca 2nd sem u-4 operator overloading
Mca 2nd  sem u-4 operator overloadingMca 2nd  sem u-4 operator overloading
Mca 2nd sem u-4 operator overloading
 
Ch-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdfCh-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdf
 
3. Polymorphism.pptx
3. Polymorphism.pptx3. Polymorphism.pptx
3. Polymorphism.pptx
 
Cs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALCs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUAL
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
power point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions conceptspower point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions concepts
 
Week7a.pptx
Week7a.pptxWeek7a.pptx
Week7a.pptx
 
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
 
Functions in C++ programming language.pptx
Functions in  C++ programming language.pptxFunctions in  C++ programming language.pptx
Functions in C++ programming language.pptx
 
Cpp tutorial
Cpp tutorialCpp tutorial
Cpp tutorial
 
C++ functions
C++ functionsC++ functions
C++ functions
 
C++ functions
C++ functionsC++ functions
C++ functions
 
Oops presentation
Oops presentationOops presentation
Oops presentation
 
CppTutorial.ppt
CppTutorial.pptCppTutorial.ppt
CppTutorial.ppt
 
#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
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloading
 
overloading in C++
overloading in C++overloading in C++
overloading in C++
 
C++
C++C++
C++
 

Recently uploaded

Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptrcbcrtm
 
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
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineeringssuserb3a23b
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
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
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 

Recently uploaded (20)

Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.ppt
 
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
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineering
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
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
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 

operator overloading

  • 1. + - * / % & ! = ^ < > << >> ? | += -= *= /= %= != &= >= <= && || ++ - -
  • 2. . i.e. to overload an operator is to provide it a new meaning for user defined data types. In simple words we can say that by using Operator Overloading we can perform basic operations like (Addition, Subtraction, multiplication, Division and so on………..) on our own defined objects of the class By Overloading the appropriate Operators, you can use Objects in expressions in just the same way that you use built in data types in C++ Operator overloading allows full integration of new data types into the programming environment because operators can be extended to work not just with built-in data types but also with classes. Operator Overloading is One of the most exciting feature of Object oriented programming. In C++ the Overloading principle applies not only to function but to operators as well.
  • 3. O P E R A T O R O V E R L O A D I N G Explanation Normally a=b+c ; works only with basic data types such as int and float, and attempting to apply it when a b and c are objects of primitive data types. However we can make this statement legal even when a b and c are user defined data_types. And actually oprator_overloading is the only feature that gives you opportunity to redefine the C++ Language.
  • 5. An Example that will illustrate how to overload unary operators: //Increment counter variable with ++ Operator ////////////////////////////////////////////////////////////////////////////////////// #include<iostream.h> #include<conio.h> Class counter { private: int count; //count public: counter() : count(0) //constructor { } int get_count() //return count Void operator ++() //increment (prefix) { ++count; } };
  • 6. ////////////////////////////////////////////////////////////////////////////////////////////////////////////// void main() { counter c1, c2; //define and initialize cout<<“n c1=“<<c1.get_count(); //display cout<<“n c2=“<<c2.get_count(); ++c1; //increment c1 ++c2; //increment c2 ++c2; //increment c2 cout<<“n c1=“<<c1.get_count(); //display again cout<<“n c2=“<<c2.get_count() <<endl; getch(); } // - - - -- end of program - - - - - -- // Here is the program’s output: C1=0 counts are initially 0 C2=0 C1=1 incremented once C2=2 incremented twice
  • 7. OPERATOR ARGUMENTS In main () the ++ operator is applied to a specific object, as in the expression ++c1. Yet operator++() takes no arguments. What does this operator increment? It increments the Count data in the object of which it is a member. Since member functions can always access the particular object for which they’ve been invoked, this operator requires no arguments.
  • 8.
  • 9. Binary Operators can be overloaded just as easily as Unary operators, we frequently use binary operators to perform various arithmetic operations, but by overloading binary operators we are able to perform various arithmetic operations on our own user-defined data types. Binary Arithmetic Operators Relational Operators Logical Operators
  • 10. OVERLOADING ARITHMETIC OPERATOR Some of the most commonly used operators in C++ are the arithmetic operators i.e. addition operator (+), subtraction operator (-), multiplication operator (*) and division operator(/). All the Arithmetic operators are Binary operators and binary operators and binary operators are overloaded in exactly the same way as the unary operators. Binary operators operate on two operands. i.e. One from each side of the operator. For example: a + b, a – b, a * b, a / b.
  • 11. Here is a program that will show you how to overload arithmetic operator. // overloaded ‘+’ operator adds two Distances #include <iostream.h> class Distance //English Distance class { private: int feet; float inches; public: //constructor (no args) Distance() : feet(0), inches(0.0) { } //constructor (two args) Distance(int ft, float in) : feet(ft), inches(in) { } void getdist() //get length from user { cout << “nEnter feet: “; cin >> feet; cout << “Enter inches: “; cin >> inches; } void showdist() const //display distance { cout << feet << “’-” << inches << ‘”’; } Distance operator + ( Distance ) const; //add 2 distances };
  • 12. Distance Distance::operator + (Distance d2) const //return sum { int f = feet + d2.feet; //add the feet float i = inches + d2.inches; //add the inches if(i >= 12.0) //if total exceeds 12.0, { //then decrease inches i -= 12.0; //by 12.0 and f++; //increase feet by 1 } //return a temporary Distance return Distance(f,i); //initialized to sum } int main() { Distance dist1, dist3, dist4; //define distances dist1.getdist(); //get dist1 from user Distance dist2(11, 6.25); //define, initialize dist2 dist3 = dist1 + dist2; //single ‘+’ operator dist4 = dist1 + dist2 + dist3; //multiple ‘+’ operators //display all lengths cout << “dist1 = “; dist1.showdist(); cout << endl; cout << “dist2 = “; dist2.showdist(); cout << endl; cout << “dist3 = “; dist3.showdist(); cout << endl; cout << “dist4 = “; dist4.showdist(); cout << endl; return 0; }
  • 13. Explanation To show that the result of an addition can be used in another addition as well as in an assignment, another addition is performed in main(). We add dist1, dist2, and dist3 to obtain dist4 (which should be double the value of dist3), in the statement dist4 = dist1 + dist2 + dist3; Here’s the output from the program: Enter feet: 10 Enter inches: 6.5 dist1 = 10’-6.5” ← from user dist2 = 11’-6.25” ← initialized in program dist3 = 22’-0.75” ← dist1+dist2 dist4 = 44’-1.5” ← dist1+dist2+dist3
  • 14. OVERLOADING RELATIONAL OPERATORS There are various relational operators in C++ like (< ,>, <=, >=, == , etc.) these operators can be used to compare C++ built-in data types. Any of these operators can be overloaded, which can be used to compare the objects of a class. Following EXAMPLE explains how a < operator can be overloaded, and in the same way we are able to overload the other relational operators. All relational operators are binary, and should return either true or false. Generally, all six operators can be based off a comparison function, or each other, although this is never done automatically (e.g. overloading > will not automatically overload < to give the opposite).
  • 15. #include<iostream.h> Class Distance { private: int feet; int inches; public: Distance() { feet=0; inches=0;} Distance(int f, int i) { feet = f; inches=i; } Void displayDistance () { cout<<“F: “<<feet<<“I:”<<inches<<endl; } Distance operator - () { feet=-feet; inches=-inches; return Distance(feet, inches); }
  • 16. bool operator < (const Distance & d) { if(feet<d.feet) {return true; } if(feet==d.feet && inches < d.inches) {return true;} Return false; } }; ////////////////////////////////////////////////////////////////////////////////////////////////////
  • 17.
  • 18. ARITHMETIC ASSIGNMENT OPERATORS Arithmetic Assignment operators are overloaded in exactly the same way as we have overloaded all other arithmetic operators and these operators can be used to create an object just like copy constructors. The following example explains how to overload an arithmetic operator. `````````````````````````````````````````````````````````````````````````````````` // overload ‘+=‘ assignment operator #include<iostream.h> class Distance //English Distance class { private: int feet; float inches; public: //constructor (no args) Distance() : feet(0), inches(0.0) { } //constructor (two args) Distance(int ft, float in) : feet(ft), inches(in) { }
  • 19. //-------------------------------------------------------------- //add distance to this one void Distance::operator += (Distance d2) { feet += d2.feet; //add the feet inches += d2.inches; //add the inches if(inches >= 12.0) //if total exceeds 12.0, { //then decrease inches inches -= 12.0; //by 12.0 and feet++; //increase feet } //by 1 } //////////////////////////////////////////////////////////////// void getdist( ) //get length from user { cout << “nEnter feet: “; cin >> feet; cout << “Enter inches: “; cin >> inches; } void showdist() const //display distance { cout << feet << “’-” << inches << ‘”’; } void operator += ( Distance ); };
  • 20. int main() { Distance dist1; //define dist1 dist1.getdist(); //get dist1 from user cout << “ndist1 = “; dist1.showdist(); Distance dist2(11, 6.25); //define, initialize dist2 cout << “ndist2 = “; dist2.showdist(); dist1 += dist2; //dist1 = dist1 + dist2 cout << “n After addition,”; cout << “ndist1 = “; dist1.showdist(); cout << endl; return 0; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  • 21. The Operator Keyword Sometimes question arises, How a normal C++ operator act on a user-defined operand? The Operator keyword is used to overload the ++ operator in this declarator. e.g. void operator ++(). Where void is the return type, the operator keyword is the name of a function and the operator ++(). This declarator syntax tells the compiler to call this member function, whenever the ++ operator is encountered. If the operand is a basic type such as int as in ++ intvar, then compiler use it’s built in routine to increment as int. The compiler will know to use user-written operator ++() instead.
  • 23. Here’s the example: #include <iostream> using namespace std; //////////////////////////////////////////////////////////////// class Counter { private: unsigned int count; //count public: Counter() : count(0) //constructor no args { } Counter(int c) : count(c) //constructor, one arg { } unsigned int get_count() //return count { return count; } Counter operator ++ () //increment count { ++count; // increment count, then return return Counter(count); // an unnamed temporary object } // initialized to this count }; ////////////////////////////////////////////////////////////////
  • 24. int main() { Counter c1, c2; //c1=0, c2=0 cout << “nc1=” << c1.get_count(); //display cout << “nc2=” << c2.get_count(); ++c1; //c1=1 c2 = ++c1; //c1=2, c2=2 cout << “nc1=” << c1.get_count(); //display again cout << “nc2=” << c2.get_count() << endl; return 0; }
  • 25. POSTFIX NOTATION // postfix.cpp // overloaded ++ operator in both prefix and postfix #include <iostream.h> class Counter { private: unsigned int count; //count public: Counter() : count(0) //constructor no args { } Counter(int c) : count(c) //constructor, one arg { } unsigned int get_count() const //return count { return count; }
  • 26. { //increment count, then return return Counter(++count); //an unnamed temporary object } //initialized to this count Counter operator ++ (int) //increment count (postfix) { //return an unnamed temporary return Counter(count++); //object initialized to this } //count, then increment count }; //////////////////////////////////////////////////////////////// int main() { Counter c1, c2; //c1=0, c2=0 cout << “nc1=” << c1.get_count(); //display cout << “nc2=” << c2.get_count(); ++c1; //c1=1 c2 = ++c1; //c1=2, c2=2 (prefix) cout << “nc1=” << c1.get_count(); //display cout << “nc2=” << c2.get_count(); c2 = c1++; //c1=3, c2=2 (postfix) cout << “nc1=” << c1.get_count(); //display again cout << “nc2=” << c2.get_count() << endl; return 0; } Counter operator ++ () //increment count (prefix)
  • 27. Restrictions On Operator Overloading There are Some Restrictions that apply to operator overloading, for example we can not alter the precedence of an operator. We cannot change the number of operands, that an operator takes. Operator function can not have default arguments. No new operators can be created. Finally the following operators ca not be overloaded: . :: .* ?