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 overloading
Princess Sam
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
Kumar
 
#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
Hadziq Fabroyir
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
Kamal Acharya
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
abhay singh
 
Presentation on overloading
Presentation on overloading Presentation on overloading
Presentation on overloading
Charndeep Sekhon
 
Operator overloadng
Operator overloadngOperator overloadng
Operator overloadng
preethalal
 
Operator Overloading & Type Conversions
Operator Overloading & Type ConversionsOperator Overloading & Type Conversions
Operator Overloading & Type Conversions
Rokonuzzaman 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 (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

Cs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALCs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUAL
Prabhu D
 
#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
exxonzone
 
Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloading
Princess Sam
 

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

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Recently uploaded (20)

8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 

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: . :: .* ?