SlideShare a Scribd company logo
+ - * / % & !
= ^ < > << >>
? | += -= *= /=
%= != &= >=
<= && || ++ -
-
. 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.
operator overloading
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;
}
}; ////////////////////////////////////////////////////////////////////////////////////////////////////
operator overloading
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 (20)

PPT
Lec 26.27-operator overloading
Princess Sam
 
PPTX
operator overloading
Nishant Joshi
 
PPT
Lecture5
ravifeelings
 
PPT
Overloading
poonamchopra7975
 
PPTX
Operator overloading
Kumar
 
PPTX
Operator overloading
Ramish Suleman
 
PPTX
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
Hadziq Fabroyir
 
PPTX
OPERATOR OVERLOADING IN C++
Aabha Tiwari
 
PPTX
Bca 2nd sem u-4 operator overloading
Rai University
 
PPT
Operator overloading
piyush Kumar Sharma
 
PDF
Operator overloading
Kamal Acharya
 
PPTX
operator overloading & type conversion in cpp over view || c++
gourav kottawar
 
PPTX
Operator Overloading
Dustin Chase
 
PPT
Operator overloading
ArunaDevi63
 
PPT
Operator overloading
abhay singh
 
PPTX
Operator overloading
ramya marichamy
 
PPTX
operator overloading in C++
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Presentation on overloading
Charndeep Sekhon
 
PPTX
Operator overloadng
preethalal
 
PPTX
Operator Overloading & Type Conversions
Rokonuzzaman Rony
 
Lec 26.27-operator overloading
Princess Sam
 
operator overloading
Nishant Joshi
 
Lecture5
ravifeelings
 
Overloading
poonamchopra7975
 
Operator overloading
Kumar
 
Operator overloading
Ramish Suleman
 
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
Hadziq Fabroyir
 
OPERATOR OVERLOADING IN C++
Aabha Tiwari
 
Bca 2nd sem u-4 operator overloading
Rai University
 
Operator overloading
piyush Kumar Sharma
 
Operator overloading
Kamal Acharya
 
operator overloading & type conversion in cpp over view || c++
gourav kottawar
 
Operator Overloading
Dustin Chase
 
Operator overloading
ArunaDevi63
 
Operator overloading
abhay singh
 
Operator overloading
ramya marichamy
 
Presentation on overloading
Charndeep Sekhon
 
Operator overloadng
preethalal
 
Operator Overloading & Type Conversions
Rokonuzzaman Rony
 

Viewers also liked (6)

PPTX
Function overloading
Selvin Josy Bai Somu
 
PPT
Operator Overloading
Mani Singh
 
PDF
Operator overloading in C++
Ilio Catallo
 
PPT
Function Overlaoding
Chandrakiran Satdeve
 
PDF
06. operator overloading
Haresh Jaiswal
 
PPTX
Function overloading
Jnyanaranjan Dash
 
Function overloading
Selvin Josy Bai Somu
 
Operator Overloading
Mani Singh
 
Operator overloading in C++
Ilio Catallo
 
Function Overlaoding
Chandrakiran Satdeve
 
06. operator overloading
Haresh Jaiswal
 
Function overloading
Jnyanaranjan Dash
 
Ad

Similar to operator overloading (20)

PDF
Basics _of_Operator Overloading_Somesh_Kumar_SSTC
drsomeshdewangan
 
PPTX
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx
RashidFaridChishti
 
PDF
Object Oriented Programming using C++ - Part 3
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
PPT
Mastering Operator Overloading in C++...
TaseenTariq1
 
PPTX
3. Polymorphism.pptx
ChhaviCoachingCenter
 
PDF
Ch-4-Operator Overloading.pdf
esuEthopi
 
PPTX
Week7a.pptx
NasirAli233814
 
PDF
22 scheme OOPs with C++ BCS306B_module3.pdf
sindhus795217
 
PPT
3d7b7 session4 c++
Mukund Trivedi
 
PPT
Overloading
Mukhtar_Hunzai
 
PPT
08 c-operator-overloadingppt2563
Youth For Peace
 
PPTX
Operator Overloading
Juginder Pal Singh
 
PPT
Unary operator overloading
BalajiGovindan5
 
PPTX
B.sc CSIT 2nd semester C++ Unit4
Tekendra Nath Yogi
 
PDF
Operator overloading
Pranali Chaudhari
 
PDF
Polymorphism and Type Conversion.pdf pot
e13225064
 
PDF
M11 operator overloading and type conversion
NabeelaNousheen
 
PPT
Polymorphism and function overloading_new.ppt
ChetanyaChopra1
 
PPTX
oprators in cpp,types with example and details.pptx
komalrokade4
 
PDF
overloading in C++
Prof Ansari
 
Basics _of_Operator Overloading_Somesh_Kumar_SSTC
drsomeshdewangan
 
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx
RashidFaridChishti
 
Object Oriented Programming using C++ - Part 3
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Mastering Operator Overloading in C++...
TaseenTariq1
 
3. Polymorphism.pptx
ChhaviCoachingCenter
 
Ch-4-Operator Overloading.pdf
esuEthopi
 
Week7a.pptx
NasirAli233814
 
22 scheme OOPs with C++ BCS306B_module3.pdf
sindhus795217
 
3d7b7 session4 c++
Mukund Trivedi
 
Overloading
Mukhtar_Hunzai
 
08 c-operator-overloadingppt2563
Youth For Peace
 
Operator Overloading
Juginder Pal Singh
 
Unary operator overloading
BalajiGovindan5
 
B.sc CSIT 2nd semester C++ Unit4
Tekendra Nath Yogi
 
Operator overloading
Pranali Chaudhari
 
Polymorphism and Type Conversion.pdf pot
e13225064
 
M11 operator overloading and type conversion
NabeelaNousheen
 
Polymorphism and function overloading_new.ppt
ChetanyaChopra1
 
oprators in cpp,types with example and details.pptx
komalrokade4
 
overloading in C++
Prof Ansari
 
Ad

Recently uploaded (20)

PDF
System Center 2025 vs. 2022; What’s new, what’s next_PDF.pdf
Q-Advise
 
PDF
AI Image Enhancer: Revolutionizing Visual Quality”
docmasoom
 
PDF
Adobe Illustrator Crack Full Download (Latest Version 2025) Pre-Activated
imang66g
 
PDF
Infrastructure planning and resilience - Keith Hastings.pptx.pdf
Safe Software
 
PPTX
Role Of Python In Programing Language.pptx
jaykoshti048
 
PPTX
Employee salary prediction using Machine learning Project template.ppt
bhanuk27082004
 
PDF
Step-by-Step Guide to Install SAP HANA Studio | Complete Installation Tutoria...
SAP Vista, an A L T Z E N Company
 
PDF
WatchTraderHub - Watch Dealer software with inventory management and multi-ch...
WatchDealer Pavel
 
PPTX
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
PDF
Troubleshooting Virtual Threads in Java!
Tier1 app
 
PDF
Generating Union types w/ Static Analysis
K. Matthew Dupree
 
PDF
SAP GUI Installation Guide for macOS (iOS) | Connect to SAP Systems on Mac
SAP Vista, an A L T Z E N Company
 
PPT
Activate_Methodology_Summary presentatio
annapureddyn
 
PDF
Protecting the Digital World Cyber Securit
dnthakkar16
 
PPTX
Explanation about Structures in C language.pptx
Veeral Rathod
 
PPTX
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
PDF
Summary Of Odoo 18.1 to 18.4 : The Way For Odoo 19
CandidRoot Solutions Private Limited
 
PDF
Salesforce Implementation Services Provider.pdf
VALiNTRY360
 
PPTX
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
PPTX
Presentation about variables and constant.pptx
kr2589474
 
System Center 2025 vs. 2022; What’s new, what’s next_PDF.pdf
Q-Advise
 
AI Image Enhancer: Revolutionizing Visual Quality”
docmasoom
 
Adobe Illustrator Crack Full Download (Latest Version 2025) Pre-Activated
imang66g
 
Infrastructure planning and resilience - Keith Hastings.pptx.pdf
Safe Software
 
Role Of Python In Programing Language.pptx
jaykoshti048
 
Employee salary prediction using Machine learning Project template.ppt
bhanuk27082004
 
Step-by-Step Guide to Install SAP HANA Studio | Complete Installation Tutoria...
SAP Vista, an A L T Z E N Company
 
WatchTraderHub - Watch Dealer software with inventory management and multi-ch...
WatchDealer Pavel
 
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
Troubleshooting Virtual Threads in Java!
Tier1 app
 
Generating Union types w/ Static Analysis
K. Matthew Dupree
 
SAP GUI Installation Guide for macOS (iOS) | Connect to SAP Systems on Mac
SAP Vista, an A L T Z E N Company
 
Activate_Methodology_Summary presentatio
annapureddyn
 
Protecting the Digital World Cyber Securit
dnthakkar16
 
Explanation about Structures in C language.pptx
Veeral Rathod
 
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
Summary Of Odoo 18.1 to 18.4 : The Way For Odoo 19
CandidRoot Solutions Private Limited
 
Salesforce Implementation Services Provider.pdf
VALiNTRY360
 
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
Presentation about variables and constant.pptx
kr2589474
 

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.
  • 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; } }; ////////////////////////////////////////////////////////////////////////////////////////////////////
  • 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: . :: .* ?