OPERATOR
OVERLOADING
Operator Overloading :
“Operator Overloading is an idea of giving special meaning to an existing operator
in C++ without changing their original meaning.”
(It can also be called Compile Time Polymorphism)
So, we can assign different meanings to an operator based on different data types.
Here, variables “a” and “b” are of type “int” and
Example:
“float”, which are built in data types.
int a;
float Hence the addition operator ‘+’ can easily add
b,sum; the contents of “a” and “b”. This is because,
sum=a+b; the addition operator “+” is predefined to add
variables of built in data type only.
Now , consider another
example:
In this example, we have 3 variables (objects)
class A “a1”, “a2” and “a3” of type “class A” (user defined
{ type).
};
int main() Here we are trying to add two objects “a1” and
{ “a2”, which are of type “class A” using “+”
A a1,a2,a3; operator.
a3= a1 + a2;
return 0; This is not allowed, because addition operator “+”
} is predefined to operate only on built-in data
types. But here, “class A” is a user defined type,
so compiler generate an error.
This is where and why, the concept of “Operator overloading” comes in.
Now, if the user wants to make the operator “+” to add two class objects, the user
has to redefine the meaning of “+” operator such that it adds two class objects. This
is done by using the concept “Operator overloading”.
Redefining the meaning of operators really does not change their original meaning;
instead they have been given additional meaning along with their existing ones.
So the main idea behind “Operator overloading” is to use C++ operators with class
variables or class objects.
NOTE: the point of operator overloading is to be intuitive. You do not want to assign a confusing
operator name. For instance, you do not want to overload the "+" when the function actually
performs subtraction.
Almost any operator can be overloaded in C++. However there are
few operator which can not be overloaded. Operator that are not
overloaded are follows:
Scope operator - ::
The reason why we cannot
Size operator - Sizeof overload these operators because
these operators take names
member selector(Dot Opearor) - . (example class name) as their
operand instead of values, as is
the case with other normal
member pointer selector - * operators
ternary operator - ? :
IMPLEMENTING OPERATOR
OVERLOADING:
Operator overloading can be done by implementing a “function. The syntax of
that function is:
Operator to be
Keyword overloaded
returnType Operator OpearatorSymbol (argumentList)
\\ Function Body
}
7
What is the difference between Operator
Overloading functions and Normal functions :
Operator functions are almost as normal functions. The only
differences are, the name of an operator function is always
the operator keyword followed by the symbol of the operator
and operator functions are automatically called when the
corresponding operator is used.
We can implement the operator overloading function by
using it in the following ways:
As a “Member Function”: Operator overloading function can be a member function
if the Left operand is an Object of that class.
As a “Non-Member Function”: If the Left operand is different, then Operator
overloading function must be a non-member function.
As a “Friend Function”: Operator overloading function can be made friend function
if it needs access to the private and protected members of class.
(1) Operator Overloading function as a member
function of a class:
The operator overloading function will have no arguments for unary
operators:
“ Ex: If it is a++, then compiler will call the overloading function like this: [Link] ++ () as
the operand ‘a’ is the object of that same class as the overloading function”
The operator overloading function will have only one argument for
binary operators:
“ Ex: If it is (a1+a2), then compiler will call the overloading function like this: [Link] + (a2)
as the left operand ‘a1’ is the object of same class as the overloading function ”
Overloading Unary Operator:
(Has only one operand like ++a)
Following are the examples of Unary operators:
• The increment (++) and decrement (--) operators
• The unary minus (-) operator
( A minus operator when used as a unary, takes just one operand. We know that this operator changes the
sign of an operand when applied to a basic data item )
• The logical not (!) operator.
The unary operators operate on the object for which they were called and normally this
operator appears on the left side of the object, as in !obj, -obj, and ++obj but sometime
they can be used as postfix as well like obj++ or obj--.
Example-1: It will be a Member function
as operand of ‘++’ will be
the object of same class
#include <iostream> Weight::Weight(int a){ int main(){
using namespace std; x=a; Weight w1(55),w2,w3;
} [Link]();
class Weight{
int x; void Weight::display(){
w2= ++w1;
cout<<"The Weight is: "<<x<<"
kg"<<endl; [Link]();
public:
Weight(); }
cout<<endl;
Weight(int a);
Weight Weight::operator ++(){
void display(); Weight temp; w3=w1++;
//Pre increment temp.x= ++x; [Link]();
Weight operator ++(); return temp;
//Post increment }
return 0;
Weight operator ++(int);
}
}; Weight Weight::operator ++(int){
Weight temp; Compiler understands this like
this: w2= [Link]++()
Weight::Weight(){ temp.x= x++;
return temp;
x=0;
}
}
Example-2:
#include <iostream> // method to display distance int main()
using namespace std; void displayDistance() {
{ Distance D1(11, 10), D2(-5,
class Distance cout << "F: " << feet << " I:" 11);
{ << inches <<endl;
int feet; } -D1; // apply negation
int inches; // display D1
// overloaded minus (-) operator [Link]();
public: void operator - ()
// required constructors { -D2; // apply negation
Distance(){ feet = -feet; // display D2
feet = 0; inches = -inches; [Link]();
inches = 0; }
} }; return 0;
}
Distance(int f, int i){
feet = f;
inches = i;
}
Practice Example 1:
Write a program that will demonstrate overloading unary operator. The program
uses the following properties –
✔ class names- test;
✔ three integer type private member variables- e,f,g;
✔ three public member function getdata(int x, int y, int z), display(), operator - ()
Function getdata(-50, 88, -19) assigns the values for e, f, g;
operator-() changes the sign of the value of the object.
display() member function displays the result as output before change sign and
after change sign which is as follows-
▪ S: -50 88 -19
▪ S: 50 -88 19
Overloading Binary Operator:
(Has two operands like this: a+b)
Binary operators use two operands for overloading. Binary operators is applied
for two objects.
The binary operators take two arguments and following are the examples of Binary
operators. You use binary operators very frequently like addition (+) operator,
subtraction (-) operator and division (/) operator.
Following example explains how addition (+) operator can be overloaded. Similar
way, you can overload subtraction (-) and division (/) operators.
Example-1:
#include<iostream> Complex Complex::operator +(Complex c){
using namespace std; Complex temp;
[Link]=real+[Link];
class Complex{ [Link]=imag+[Link]; It will be a Member function
as left operand of ‘+’ is an
float real; return temp;
object of same class
float imag; }
void display(Complex c){
public: cout<<[Link]<<" + "<<[Link]<<"i"<<endl;
Complex(); }
Complex(float r,float i);
int main(){
// Overloading + operator Complex c1(5.4,3.7),c2(2.8,5.6),c3;
Complex operator +(Complex c);
friend void display(Complex c); cout<<"1st Complex Number is: ";
}; display(c1);
Complex::Complex(){ cout<<"2nd Complex Number is: ";
real=0; display(c2);
imag=0; Compiler understands this like
} c3=c1+c2; this: c3= [Link] + (c2)
cout<<"Added Complex Number is: ";
Complex::Complex(float r,float i){ display(c3);
real=r;
imag=i; return 0;
} }
Example-2:
#include <iostream>
using namespace std;
void Box::setdata(double len,double bre,double hei)
class Box {
{ length = len;
double length; // Length of a box breadth = bre;
double breadth; // Breadth of a box height = hei;
double height; // Height of a box }
public: Box Box::operator +(Box &b){
double getVolume(); Box box;
void setdata(double len,double bre,double hei); [Link] = length + [Link];
[Link] = breadth + [Link];
// Overload + operator to add two Box objects. [Link] = height + [Link];
Box operator +(Box &b); return box;
}; }
double Box::getVolume()
{
return length * breadth * height;
}
int main() // Add two object as follows:
{ b3=b1+b2;
Box b1,b2,b3;
double volume=0; // volume of box 3
volume = [Link]();
// box 1 specification cout << "Volume of Box3 : " << volume <<endl;
[Link](6.0,7.0,5.0);
return 0;
// box 2 specification }
[Link](12.0,13.0,10.0);
// volume of box 1 Output:
volume = [Link]();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = [Link]();
cout << "Volume of Box2 : " << volume <<endl;
Practice Problem 1:
Write a program that will demonstrate overloading binary operator. The program uses the
following properties –
class names- test;
one integer type private member variables- value;
two constructor function test(), test(int a);
one operator overloading function test operator-(test s);
one member function display().
Suppose test function has got three objects like ob1(80), ob2(50), ob3. We want to subtract the
value of object ob2 from the value of ob1 and ob3 will carry the subtraction result. The display() will
display the output as follows-
ob1=80
ob2=50
ob3=30
(2) Operator Overloading function as a non-member function of
a class: Members of the
void operator << (ostream& COUT, YouTubeChannel& ytChannel){
COUT<<"Name: "<<[Link]<<endl;
class must be
kept in public so COUT<<"No of Subs: "<<[Link]<<endl;
#include <iostream> that the }
#include <string> non-member
using namespace std; function can int main(){ It will be a
access it YouTubeChannel yt1("CodeBeauty",50000); Non-member
class YouTubeChannel{ YouTubeChannel yt2("Apna College",80000); function as left
public: cout<<yt1; operand of ‘<<’ is
string Name; cout<<yt2; not an object of that
int SubscriberCount; same class
return 0;
YouTubeChannel(string name,int sub); }
};
YouTubeChannel::YouTubeChannel(string name,int sub){
Name=name; Output:
SubscriberCount=sub;
}
(3) Operator Overloading function as a friend function of a class:
#include <iostream> ostream& operator << (ostream& COUT, YouTubeChannel&
#include <string> ytChannel){
Non-member
using namespace std; function must be COUT<<"Name: "<<[Link]<<endl;
added as friend COUT<<"No of Subs:
class YouTubeChannel{ function to access "<<[Link]<<endl<<endl;
private: the private data return COUT;
string Name; of the class
}
int SubscriberCount;
int main(){
public: YouTubeChannel yt1("CodeBeauty",50000);
YouTubeChannel(string name,int sub); YouTubeChannel yt2("Apna College",80000);
friend ostream& operator << (ostream& COUT, cout<<yt1<<yt2;
YouTubeChannel& ytChannel); return 0;
}; }
YouTubeChannel::YouTubeChannel(string name,int sub){
Name=name;
Output:
SubscriberCount=sub;
}
Exercise-1:
Design a class “Polar” which describes a point in the plane using polar coordinates radius and angle.
❑ Use the overloaded + operator to add two objects of
Polar
Note that we cannot add polar values of two points directly.
This requires first the conversion of points into rectangular
co-ordinates(x,y), then adding the corresponding rectangular
co-ordinates and finally converting the result back into polar
co-ordinates. You need to use the following trigonometric
formula:
x = r * cos(a)
y = r * sin(a)
a = atan(y/x) // arc tangent
r = sqrt(x*x + y*y)
Solution:
#include <iostream> Polar Polar::operator + (Polar& p){ int main(){
#include <cmath> double p1,a1,p2,a2,x1,y1,x2,y2,x,y; Polar p1(34.56,30),p2(54.23,60),p3;
using namespace std;
#define pi 3.1416 x1=radius*cos((angle*pi)/180); cout<<"First Polar co-ordinate is:
x2=[Link]*cos(([Link]*pi)/180); "<<endl;
class Polar{ [Link]();
double radius,angle; y1=radius*sin((angle*pi)/180); cout<<endl;
y2=[Link]*sin(([Link]*pi)/180);
public: cout<<"Second Polar co-ordinate is:
Polar(); x=x1+x2; "<<endl;
Polar(double r,double a); y=y1+y2; [Link]();
Polar operator +(Polar& p); cout<<endl;
void display(); Polar pm;
}; [Link] = sqrt(x*x+y*y); p3=p1+p2;
[Link] = (atan(y/x)*180)/pi; cout<<"New Polar co-ordinate is:
Polar::Polar(){ return pm; "<<endl;
radius = 0.0; } [Link]();
angle = 0.0; void Polar::display(){ cout<<endl;
} cout<<"Radius: "<<radius<<" cm"<<endl;
Polar::Polar(double r,double a){ cout<<"Angle: "<<angle<<" return 0;
radius = r; degree"<<endl; }
angle = a; }
}
Thank You!!!