Questions: 1. Write the list of rules for overloading operators with one example. 2. With suitable example, explain how function overloading and operator overloading suports compile‒time polymorphism. 3. What is operator overloading? List out the rules to overload a binary operator.
Operator
Overloading
•
Operator overloading is confusing even for excellent programmer but it is a
strong feature of C++ if you could master it. The operators are used in mathematical
expressions like
c=a+b;
area=3.14*r*r;
•
It would be very nice if we could use these operators in our own objects. That
means the string class can use to concatenate two strings. That also means
operators can be programmed to whatever we wish to do with them.
•
Operator overloading can be defined as an ability to define a new meaning for
an existing (built‒in) "operator".
•
Various types of operators are
о
Mathematical operators such as + – * / ++
о
Relational operators such as < > ==
о
Logical operators such as && ||
о
Access operators [ ] ‒>
о
Assignment operator =
о
Stream I/O operators << >>
о
Type conversion operators and several others.
•
All of these operators have a predefined and unchangeable meaning for the built‒in
types. All of these operators can be given a specific interpretation for
different classes or combination of classes. C++ provides the flexibility to
the programmers in extending these built‒in operators.
How to overload
operator ?
Define
a function with keyword operator. Then write the operator (such as +, [] or any
other valid operator) as a function name. That means we can program that
specific operator.
Restrictions on use of
operators
•
It's not possible to change an operator's precedence.
•
It's not possible to create new operators, For example ^
which is used in some languages for exponentiation.
•
You can not redefine ::, sizeof, ?:, or .
(dot).
•
=, [], and ‒> must be member functions if they are overloaded.
•
++ and ‒ ‒ need special treatment
because they are prefix or postfix operators.
•
Assignment (=) should always be overloaded if an object dynamically allocates memory.
•
It can not change the number of required operands (unary, binary, ternary).
•
Overloaded operator must be either,
o
Non static member function of class
or
o
At least one parameter should be class
or enumeration.
Makes
no assumptions about similar operators. For example, the fact that you
overloaded + does not mean that you have also defined += for your class type.
1. Need of Operator Overloading
2. Rules for Operator Overloading
3. Overloading Unary Operator
4. Overloading Binary Operator
5. Overloading using Friend
6. Overloading of Input Operators << and >>
7. Overloading Assignment
8. Overloading Pointer to Member and Subscript
9. Overloading new and delete Operators
10. More Examples on Operator Overloading
•
There are predefined operators such as +, ‒,*, / and so on which operate on the
fundamental data types such as integer, double, char and so on. In order to
make the user defined data type as natural as fundamental data type, the user
defined data types can be associated with the set of predefined operators the concept called operator overloading is used. Note that the fundamental meaning of
these operators is not at all changed by operator overloading. Rather, with
this meaning these operators are associated with the user defined data types.
For instance ‒ If we want to perform the operations on two complex numbers then
with the help of operator overloading the operations such as addition,
multiplication and so on can be carried out. In this case the class for Complex number is created.
1.
Only existing operators can be overloaded.
2.
The basic meaning of the operator
can not be changed.
3.
Overloaded operators must follow the
syntax of original operator. For example for binary operator operand1
operator operand2 is the syntax and this can not be changed during overloading.
4.
Overloaded operators must have at least
one operand that is of user defined type.
5.
Binary arithmetic operators(+, ‒, *
and /) must return a value.
6.
When binary operators overloaded
through a member function, the left hand
and operand must be an object of
relevant class.
7.
Binary operators overloaded through
a member function must take one explicit
argument.
8.
Binary operators overloaded through friend function takes two arguments.
9.
Unary operators overloaded through a
member function must take no
explicit argument and no return
value.
10. Unary operators overloaded through friend function takes one explicit argument.
11.
There are some operators that can not be overloaded.
•
The unary operators require only one operand. In C++ the unary operators are ‒,+,!,~,
& and *.
•
It can be declared as member functions taking no arguments. That means for any operator ‒, ‒ obj is interpreted as obj.operator‒()
•
It can be declared as non member
functions taking one argument that must be the variable of class type (i.e.
Object) or reference. That means, for any operator ‒ the ‒ obj is interpreted as operator‒(obj).
•
If both types of definitions are present then, the function declared as member
takes the precedence.
Syntax: The function definition for operator function is as follows ‒

Example:
Point
operator ‒ ()
{
}
Following
program illustrates the operator overloading of an unary operator !.
/*************************************************************************
Program for overloading ! operator. The overloading function can
be a member or a non member function.
***********************************************************************/
#include <iostream>
using namespace std;
class X
{
};
void operator!(X)
//Defined operator overloading function
as a non‒member function
{
cout<<"We
are using operator! (X)"<< endl;
}
class Y
{
public:
void operator!() //Defined
operator overloading function as a member function
{
cout<<"we
are using Y::operator!()"<<endl;
}
};
int main()
{
X obj_x;
Y obj_y;
lobj_x; //invoking
the non member function
!obj_y; //invoking
the member function
return 0;
}
Output
We are using
operator!(X)
we are using
Y::operator()
Program explanation:
In
above example the operator function is ‒
•
A non‒member function with only one
argument or
• A member function with no argument.
• When there is an argument passed to a non‒member
function (like for class X) this argument is usually object of a class or
reference to object of a class. The operator function call !obj_x will be interpreted as operator!(x)
and call to !obj_y will be
interpreted as Y.operator!()
Example:1
Write a C++ program for overloading a unary
minus operator.
Solution :
/***************************************************************************
Program for overloading an unary minus operator/
**********************************************************************
#include <iostream>
using namespace std;
class point
{
private:
int x, y; // co‒ordinate
values
public:
point() { x = 0; y =
0; }//constructor
point(int i, int j)
{ x = i; y = i; yj; } //constructor
void get_xy(int
&i, int &j) { i = x; j = y; }
point operator‒();
// operator overload for unary
// minus
};
point point::operator‒( )
{
x = ‒x;
y = ‒y;
return *this; // Use
of this pointer
}
int main()
{
point obj(10, 10);
int x, y;
clrscr();
obj.get_xy(x, y);
obj = ‒ obj; // Negation calls operator ‒ ()
obj.get_xy(x, y);
cout<<"\n The use of unary operator is
..."<endl;
cout << "X: " << x << ", Y:
" << y;
return 0;
}
Output
The use of unary
operator is ...
X: ‒10, Y: ‒10
Program explanation:
Note
that in above code the unary minus operator function is overloaded by passing
no argument to it.
obj
= ‒ obj;
When
this statement occurs the call to operator ‒() function is given. Thereby
negated values of x and y are obtained.
Example: 2
Write a
C++ program for overloading a increment operator ++.
Solution:
#include <iostream>
using namespace std;
class coord
{
private:
int x, y; // co‒ordinate
values
public:
coord() { x = 0; y
= 0; }//constructor for obj
coord(int i, int j)
{ x = i; y = j; }//constructor with param
void get_xy(int
&i, int &j) { i = x; j = y; }
coord operator++(
);//unary operator overloading
};
// Overload ++ operator for coord class
coord coord::operator++()
{
x++;
return *this;
//returning the current instance
}
int main()
{
int x, y;
cout<<"\n Enter the co‒ordinates x and y ";
cin>>x>>y;
coord obj(x,y);
++obj; //Calls coord operator++()
obj.get_xy(x, y);
cout<<"The increment operator increments the co‒ordinates
as..."<<endl;
cout << "X: " << x << ", Y:
" << y;
getch();
return 0;
}
Output
Enter the co‒ordinates
x and y 10 20
The increment operator
increments the co‒ordinates as...
X: 11, Y: 21
•
It can be declared as member functions taking one argument. That is, for any
operator +, x + y is interpreted as x.operator+( y ).
•
It can be declared as non‒member functions taking two arguments; one of these
must be a variable of the class type or a reference to one. That is, for any
operator @ except the assignment operator =, x @ y is interpreted as operator
@(x, y). For example x+y is interpreted as operator +(x, y).
•
If both kinds of definitions are present, the function declared as member takes
precedence.
Examples:
Binary plus and
& ("bitwise and")
class A {
A operator+( A& )
A operator&( A& )
};
C++ Program
#include <iostream>
using namespace std;
class vector {
public:
int p,q;
vector()
(p=0;q=0;}// constructor without parameters
vector
(int,int);//constructor with parameters
vector operator +
(vector);//definition of operator +
};
vector::vector (int a, int b) {
p = a;
q = b;
}
vector vector::operator+ (vector obj)
{
vector temp;
temp.p = p + obj.p;
temp.q = q + obj.q;
return (temp);
}
int main()
{
vector a (10,20);
vector b (1,2);
vector c;
c = a + b;
cout<<"\n
The Addition of Two vectors is...";
cout << c.p
<<" and "<<c.q;
retrun 0;
}
Output
The Addition of Two
vectors is...11 and 22
•
The vector class is created to store two vectors a(10,20) and b(1,2). The
operator + is overloaded and now it will perform (10+1, 20+2) and thereby c.p
will hold 11 and c.q will hold 22.
In
above example, a constructor with parameters is defined
vector
::vector(int a,int b)
We
have also defined another constructor
vector::vector()
{
p=0;
q=0;
}
•
We have to explicitly define this initializing constructor because we have
already defined one constructor with parameter. Now to create the objects of
the class vector we need some initializing constructor.
c=a+b
•
As we perform addition the function operator + will be invoked and the addition
of one vector (10+1) will be stored in c.p and (20+2) will be stored in c.q. We
can replace c=a+b by c=a.operator+(b) because it is one and the same.
Example:
3
Consider fruit basket with number of apples
and number of mangoes as data members. Overload the '+' operator to add the two
objects of this class.
Solution :
#include<iostream>
using namespace std;
class Fruit Basket
{
public:
int NoOfApples;
int NoOfMangoes;
FruitBasket()
{
NoOfApples=0;NoOfMangoes=0;
}
Fruit Basket(int,int);
Fruit Basket operator+(FruitBasket);
};
FruitBasket::FruitBasket(int a,int b)
{
NoOfApples=a;
NoOfMangoes=b;
}
Fruit Basket Fruit Basket::operator +(Fruit Basket obj)
{
Fruit Basket temp;
temp.NoOfApples=NoOfApples+obj.NoOfApples;
temp.NoOfMangoes=NoOfMangoes+obj.NoOfMangoes;
return temp;
}
int main()
{
Fruit Basket
Basket1(100,200);
Fruit Basket Basket2(400,300);
Fruit Basket Total;
Total=
Basket1+Basket2;
cout<<"The
total Apples are: "<<Total.NoOfApples<<endl;
cout<<"The
total Mangoes are: "<<Total.NoOfMangoes<<endl;
retrun 0;
}
Output
The total Apples are:
500
The total Mangoes are:
500
•
The friend functions are not the members of a class, similarly they do not have
this pointer. Hence all the operands of the operator must be passed explicitly
to the friend operator function.
Example: 4
Write a
C++ program for overloading the greater than operator using the friend
function.
Solution :
/***************************************************************************
Program for overloading the operator > for comparing two
values
************************************************************************/
#include <iostream>
#include <cstring>
using namespace std;
class GreaterOp
{
int a;
public:
GreaterOp(){}
GreaterOp(int x)
{a=x;}
friend int operator
>(GreaterOp obj1,GreaterOp obj2);
};
int operator >(GreaterOp obj1,GreaterOp obj2)
{
if(obj1.a>obj2.a)
return 1;
else
return 0;
}
int main()
{
GreaterOp val1(1);
GreaterOp val2(10);
if(val1>val2)
cout<<"\n
The first value is greater than the second";
else
cout<<"\n
The second value is greater than the first";
return 0;
}
Output
The second value is
greater than the first
•
In C++ the output operation called insertion makes use of the operator
<<. This operator is called insertion
operator. Similarly the input operation is called extraction because the data is extracted from the keyboard. It
makes use of the operator >>. This operator is called extraction operator.
•
These operators can be overloaded to read or print certain object. Following
example illustrates this kind of operator overloading.
Example: 5
Define a class with three variables for day,
month and year. Overload the operator <<, >> to read and print date
object.
Solution:
/**********************************************************************
Program for overloading the operators << and >> to
read and print date
**********************************************************************/
#include <iostream>
#include <cstring>
using namespace std;
class DATE
{
//three variables for reading day, month and years too res
int dd,mm,yy;
public:
DATE(){}
friend istream&
operator >>(istream &is,DATE &obj);
friend ostream&
operator <<(ostream &os, const DATE &obj);
};
istream& operator >>(istream &is,DATE &obj)
{
is>>obj.dd;
is>>obj.mm;
is>>obj.yy;
return is;
}
ostream& operator <<(ostream &os,const DATE
&obj)
{
os<<"\nDay:
"<<obj.dd<<"\nMonth:
"<<obj.mm<<"\nYear: "<<obj.yy;
return os;
}
int main()
{
DATE date;
cout<<"Enter
Date as dd mm yyyy: ";
cin>>date;
cout<<date;
return 0;
}
Output
Enter Date as dd mm
yyyy: 1 1 2012
Day: 1 Month: 1
Year: 2012
•
The assignment operator is used for assigning value to a variable. Following
C++ program illustrates how to overload an assignment operator.
/***********************************************************************
Program for overloading the assignment Operator
**********************************************************************/
#include <iostream>
using namespace std;
class Equal Op
{
int a;
int b;
public:
EqualOp(int,int);//constructor
declared
void show();
EqualOp
operator=(EqualOp);
};
EqualOp::EqualOp(int x,int y)//constructor defined
{
a=x;
b=y;
}
EqualOp EqualOp::operator= (EqualOp ob) //overloading= operator
{
a=ob.a;
b=ob.b;
return
*this;//returning object with new values
};
void EqualOp::show()
{
cout<<"a=
"<<a<<endl;
cout<<"b=
"<<b<<endl;
}
int main()
{
cout<<"\tProgram
for overloading Assignment operator"<<endl;
EqualOp obj1(10,20);
cout<<"The
values before ="<<endl;
obj1.show();
EqualOp
obj2(100,200);
obj1=obj2;
cout<<"The
values after ="<<endl;
obj1.show();
return 0;
}
Output
Program for
overloading Assignment operator
The values before =
a= 10
b= 20
The values after =
a= 100
b= 200
Overloading ‒>
operator
•
The‒> is a pointer operator for accessing the member of the pointer
variable. The ‒> returns the pointer to the object of the class on which
operator ‒>() depends upon. Following is a simple program which illustrates
the overloading of ‒> operator.
#include <iostream>
using namespace std;
class POINTER
{
public:
int val;
POINTER *operator‒>()
{
return this;
}
};
int main()
{
POINTER obj;
obj‒>val=99;
cout<<"Value
assigned to the object is "<<obj‒>val;
return 0;
}
Overloading &
operator
#include<iostream>
using namespace std;
class TEST {
int ar[4];
public:
TEST(int a,int b,int
c,int d){
ar[0]=a;
ar[1]=b;
ar[2]=c;
ar[3]=d;
}
int
&operator[](int i)
{
return ar[i];
}
};
int main()
{
TEST
obj(10,20,30,40);
clrscr();
cout<<"\nFirst
element is: "<<obj[0];
cout<<"\n
Second element is: "<<obj[2];
cout<<"\n
Storing new element in an array";
obj[1]=77;
cout<<"\n
New element at index 1 is: "<<obj[1];
return 0;
}
The
new operator is used to allocate the memory whereas the delete operator is used
to deallocate the memory.
For
example
int
*a;
a=new
int[5];
This
will create a dynamic array of size 5. The five elements which we can enter in
this array are of integer type.
The
memory allocated dynamically can be deallocated using the delete operator.
For
example
delete
[] pointer;
Following
program shows the overloading of new and delete operators ‒
/************************************************************************
This program is for operator overloading of new and delete
operators
*************************************************************************/
#include<iostream>
using namespace std;
class DynamicClass
{
int x, yi
public:
DynamicClass()
{
x = y = 0;
}
void Read_Data()
{
cout<<"\n
x: ";
cin>>x;
cout<<"
y: ";
cin>>y;
}
void Display_Data()
{
cout << x
<< " ";
cout << y
<< endl;
}
void *operator
new[](size_t size);
void operator
delete[] (void *p);
};
// new operator overloaded for arrays.
void *DynamicClass::operator new[](size_t size)
{
void *p;
cout<<"Allocating
memory using overload new[].\n";
p = new int[size];
return p;
}
// delete operator overloaded for arrays.
void DynamicClass::operator delete[] (void *p)
{
cout <<
"Freeing array using overloaded delete[]\n";
delete(p);
}
void main()
{
DynamicClass *obj;
int i;
obj = new
DynamicClass[3]; // allocate
an array using new
cout<<"\nEnter
the three pairs of values"<<endl;
for(i = 0; i < 3;
i++)
{
obj[i].Read_Data();
}
cout<<"\n
You have entered following values..."<<endl;
for(i = 0; i < 3;
i++)
obj[i].Display_Data();
delete [] obj; // delete an array using
delete
getch();
}
Output
Allocating memory using
overload new[].
Enter the three pairs
of values
x: 10
y: 20
x: 30
y: 40
x: 50
y: 60
You have entered
following values...
10 20
30 40
50 60
Freeing array using
overloaded delete[]
Example:6
Write a
C++ program as follows to perform arithmetic operations on rational numbers of
type a/b, where a and b are integers?
(i)
Define a class by 'Rational Number'.
(ii) Use
operator overloaded methods for additions and subtraction.
(iii)
Write a main program to demonstrate the use of this class and its methods.
(iv) Give
sample output.
Solution :
#include<iostream>
#include<cstdlib
using namesapce std;
class RationalNumber
{
int p,q;
public:
RationalNumber ()//constructor1
{
p=0;
q=0;
}
RationalNumber (int n,int d)
{
p=n;
q=d;
}
void getdata()
{
cout<<"\nEnter
the numerator";
cin>>p;
cout<<"\nEnter
the denomenator";
cin>>q;
}
void display()
{
cout<<"The
result= "<<p<<"/"<<q;
}
friend RationalNumber operator+( RationalNumber &ob1, RationalNumber
&ob2);
friend RationalNumber operator ‒ (RationalNumber &ob1,
RationalNumber &ob2);
};
RationalNumber operator +( Rational Number &ob1,
RationalNumber &ob2)
{
RationalNumber temp;
temp.p=(ob1.p*ob2.q)+(ob1.q*ob2.p);
temp.q=(ob1.q*ob2.q);
return temp;
}
RationalNumber operator ‒ (RationalNumber &ob1,
RationalNumber &ob2)
{
RationalNumber temp;
temp.p=(ob1.p*ob2.q) ‒
(ob1.q*ob2.p);
temp.q=(ob1.q*ob2.q);
return temp;
}
void main()
{
RationalNumber ob1,ob2,ob3;
int choice;
char ans;
do
{
cout<<"\n Main Menu";
cout<<"\n 1.Addition \n 2.Subtraction";
cout<<"\n Enter Your Choice";
cin>>choice;
switch(choice)
{
case 1: cout<<"\nAddition of Two numbers\n";
cout<<"\n
Enter First Rational number";
ob1.getdata();
cout<<"\n
Enter Second Rational number";
ob2.getdata();
ob3=0b1+ob2;
ob3.display();
break;
case 2: cout<<"\nSubtraction of Two numbers\n";
cout<<"\n
Enter First Rational number";
ob1.getdata();
cout<<"\n
Enter Second Rational number";
ob2.getdata();
ob3=0b1‒ob2;
ob3.display();
break;
}
cout<<"\nDo You Want To Continue?";
ans=getche();
}while(ans= ='y' || ans = ='Y');
}
Output
Main Menu
1.Addition
2.Subtraction
Enter Your Choice1
Addition of Two
numbers
Enter First Rational
number
Enter the numerator1
Enter the denomenator2
Enter Second Rational
number
Enter the numerator2
Enter the denomenator5
The result= 9/10
Do You Want To
Continue?
Example: 7
Write a C++ program to implement C = A + B, C =
A ‒ B and C = A* B where A, B and C are objects containing a int value
(vector).
OR
Write a
C++ program to add two vectors using + operator overloading.
Solution :
#include<iostream>
using namespace std;
class vector
{
public:
int p;
vector() {p=0;}//
constructor without parameters
vector
(int);//constructor with parameters
vector operator + (vector);//definition of
operator +
vector operator ‒ (vector);//definition of
operator ‒
vector operator *
(vector);//definition of operator *
};
vector::vector (int a)
{ p = a; }
vector vector::operator+ (vector obj)
{
vector temp;
temp.pp + obj.p;
return (temp);
}
vector vector::operator (vector obj)
{
vector temp;
temp.p = p‒ obj.p;
return (temp);
}
vector vector::operator* (vector obi)
{
vector temp;
temp.pp‒ obj.p;
return (temp);
}
void main()
{
vector A (10);
vector B (1);
vector C;
C = A + B;
cout<<"\n The Addition of Two vectors is...";
cout << C.p<endl;
C = A ‒ B;
cout <<"\n The Subtraction of Two vectors
is...";
cout << C.p<endl;
C = A* B;
cout<<"\n The Multiplication of Two vectors
is...";
cout << C.p<endl;
}
Output
The Addition of Two vectors
is...11
The Subtraction of Two
vectors is...9
The Multiplication of
Two vectors is...10
Example: 8
Write a
C++ program to create a class STRING and implement the following operations.
Display the results after every operation by overloading the operator <<
i) STRING
s1="Anna"
ii)
STRING s2="University"
iii)
STRING s3=s1+s2(Use copy constructor)
OR
Write a
C++ program to concatenate two strings using + operator overloading.
Solution :
#include<iostream>
#include<cstring>
using namespace std;
class STRING
{
public:
char str[20];
STRING()
{
strcpy(str,"\n");
cout<<flush;
}
STRING(char T[20])
{
strcpy(str,T);
strcat(str,"\0");
}
STRING(STRING &obj) //copy constructor
{
strcpy(str,obj.str);
}
STRING operator+(STRING k)
{
strcat(str,k.str);
strcat(str,"\n");
return str;
}
friend ostream &operator <<(ostream &,STRING
&);
};
ostream &operator <<(ostream &os, STRING &ob)
{
os<<ob.str;
return os;
}
void main()
{
STRING s1("Anna"),s2("University");
STRING s3;
s3=s1+s2;
strcat(s3.str,"\0");
STRING s=s3;
//calling constructor
cout<<"\n
Concatenated string is = "<<s;
}
Output
Concatenated string is
= AnnaUniversity
Example: 9
Write a C++ program using operator overloading
to add two time values in the format HH: MM: SS to the resulting time along
with rounding off when 24 hours is reached. A time class is created and
operator + is overloaded to add the two time class objects.
Solution :
#include<iostream>
using namespace std;
class time
{
public:
time()
{
hr=0;
min=0;
sec=0;
}
int hr,min,sec;
void get_data()
{
cout<<"Enter
Hours:
cin>>hr;
cout<<"\nEnter
Minutes: ";
cin>>min;
cout<<"\nEnter
Seconds:
cin>>sec;
}
time operator +(time t)
{
time temp;
temp.sec=sec+t.sec;
if(temp.sec>60)
{
t.min=t.min+1;
temp.sec=temp.sec‒60;
}
temp.min=min+t.min;
if(temp.min>60)
{
t.hr=t.hr+1;
temp.min=temp.min‒60;
}
temp.hr=hr+t.hr;
return temp;
}
void display()
{
if(hr>=24)
//rounding off when 24 hrs is reached
{
hr=hr%24;
}
if(hr<10)
{
cout<<"0"<<hr;
}
else
cout<<hr;
if(min<10)
{
cout<<":0"<<<min;
}
else
cout<<":"<<<min;
if(sec<10)
{
tro
cout<<":0"<<sec;
}
else
cout<<":"<<<sec;
}
};
void main()
{
time obj1,obj2,obj3;
cout<<"\n\nEnter the First Time\n\n";
ost obj1.get_data();
cout<<"\n\nEnter the Second Time\n\n";
obj2.get_data();
cout<<"\n\nFirst Time \t\t";
obj1.display();
cout<<"\n\nSecond Time \t\t";
obj2.display();
obj3=obj1+obj2;
cout<<"\n\n Addition of given time: ";
obj3.display();
}
Output
Enter the First Time
Enter Hours: 25
Enter Minutes: 10
Enter Seconds: 10
Enter the Second Time
Enter Hours: 1
Enter Minutes: 20
Enter Seconds: 30
First Time 01:10:10
Second Time 01:20:30
Addition of given
time: 02:30:40
Example: 10
Define class 'string'. Use overload '= ='
operator to compare two strings.
Solution:
String is a collection of characters.
#include<iostream>
#include<cstring>
using namespace std;
class string1 {
char S[10];
public:
string1(){}
string1(char T[])
{
strcpy(S,T);
}
int operator==(string1 k)
{
if(strcmp(S,k.S)= =0)
return
1;
else
return 0;
}
};
int main()
{
string1 s1("testing"),s2("testing");
if(s1==s2)
cout<<"\nBoth
the strings are equal!!";
else
cout<<"\nTwo
strings are not equall!";
return 0;
}
Example:11
What is
operator overloading? Overload the numerical operators + and / for complex
numbers addition and division respectively.
Solution:
Operator overloading is defined as an ability to define a new meaning for an
existing operator.
/*Program
for overloading numerical operator + and / for complex numbers addition and
division*/
#include<iostream>
using namespace std;
class complex {
public:
float real,img;
complex(){real=0;img=0;}
complex(float,float);
complex operator+
(complex);
complex operator/
(complex);
};
complex::complex(float r,float i)
{
real=r;
img=i;
}
complex complex::operator+ (complex obj)
{
complex temp;
temp.real=real+obj.real;
temp.img=img+obj.img;
return (temp);
}
complex complex::operator/ (complex obj)
{
complex temp;
float new_temp;
new_temp=(obj.real*
obj.real)+(obj.img*obj.img);
temp.real=((real*
obj.real)+(img* obj.img))/new_temp;
temp.img=new_temp;
return(temp);
}
int main()
{
complex a(2,6);
complex b(4,1);
complex c;
c=a+b;
cout<<"\n
The addition of two complex numbers is...";
cout<<c.real<<"
and "<<c.img<<"i";
c=a/b;
cout<<"\n
The Division of two complex numbers is...";
cout<<c.real<<"
and "<<c.img<<"i";
retrun 0;
}
Example: 12
Develop a class Polynomial whose internal
representation is a term consisting of a coefficient and an exponent. Develop a
completer class containing proper constructor and destructor functions as well
as set and get functions. Overload the addition and subtraction operator to add
and subtract two polynomials and display the results. Overload the assignment
operator to assign one polynomial to another using friend function.
Solution :
#include<iostream>
using namespace std;
#define SIZE 20
class Polynomial
{
private:
int coeff[SIZE];
int expo[SIZE];
public:
int t1, t2;
int set();
Polynomial();
void get(int);
void operator+(Polynomial);
void operator‒(Polynomial);
};
Polynomial::Polynomial()
{
for(int i= 0; i<
SIZE;i++)
{
coeff[i] =
0;
expo[i] = 0;
}
}
int Polynomial::set()
{
int term,i;
cout<<"\n
Enter The Total number Of Terms in The Polynomial: ";
cin>>term;
cout<<"\n
Enter The Coef and Exponent In Descending Order";
for(i=0;i<term;i++)
{
cout<<"\n
Enter Coefficient and exponent: ";
cin>>coeff[i];
cin>>expo[i];
}
return(term);
}
void Polynomial::get(int term)
{
int k;
cout <<
"\n Printing The Polynomial";
for (k = 0;
k<term ‒ 1; k++)
cout
<< "\" << coeff[k] << "x^" <<
expo[k] << "+ ";
cout
<<coeff[k] << "X^" << expo[k];
}
void Polynomial::operator+(Polynomial ob)
{
int i, j, k;
int t3;
i = 0;
j = 0;
k = 0;
while (i<t1 &&j<ob.t2)
{
if (expo[i] == ==
ob.expo[j])
{
p3.coeff[k] =
coeff[i] + ob.coeff[j];
p3.expo[k] =
expo[i];
i++; j++;
k++;
}
else if
(expo[i]>ob.expo[j])
{
p3.coeff[k]
= coeff[i];
p3.expo[k] = expo[i];
i++; k++;
}
else
{
p3.coeff[k]
= ob.coeff[j];
p3.expo[k] =
ob.expo[j];
j++; k++;
}
}
while (i<t1)
{
p3.coeff[k] = coeff[i];
p3.expo[k] = expo[i];
i++; k++;
}
while (j<ob.t2)
{
p3.coeff[k] = ob.coeff[j];
p3.expo[k] =
ob.expo[j];
j++; k++;
}
t3 = k;
for (k = 0; k < t3‒1; k++)
{
cout <<
p3.coeff[k] << "x^" << p3.expo[k]<<"+";
}
cout << p3.coeff[k] << "x^" <<
p3.expo[k];
}
void Polynomial::operator‒(Polynomial ob)
{
int i, j, k;
int t3;
Polynomial p3;
i = 0;
j = 0;
k = 0;
while (i<t1 &&j<ob.t2)
{
if (expo[i] = = ob.expo[j])
{
p3.coeff[k]
= coeff[i] ‒ ob.coeff[j];
p3.expo[k] =
expo[i];
i++; j++;
k++;
}
else if
(expo[i]>ob.expo[j])
{
p3.coeff[k] =
coeff[i];
p3.expo[k] =
expo[i];
i++; k++;
}
else
{
p3.coeff[k]
= ob.coeff[j];
p3.expo[k] =
ob.expo[j];
j++; k++;
}
}
while (i<t1)
{
p3.coeff[k] =
coeff[i];
p3.expo[k] =
expo[i];
i++; k++;
}
while (j<ob.t2)
{
p3.coeff[k] =
ob.coeff[j];
p3.expo[k] =
ob.expo[j];
j++; k++;
}
t3 = k;
for (k = 0; k < t3 ‒ 1; k++)
{
cout <<
p3.coeff[k] << "x^" << p3.expo[k] << "+";
}
cout << p3.coeff[k] << "x^" <<
p3.expo[k];
}
void main()
{
Polynomial obj1,obj2,obj3,obj4;
cout << "\n Enter The First Polynomial";
obj1.t1 = obj1.set();
cout<<"\n The First Polynomial is: ";
obj1.get(obj1.t1);
cout << "\n Enter The Second Polynomial";
obj2.t2 = obj2.set();
cout << "\n The Second Polynomial is: ";
obj2.get(obj2.t2);
cout << "\n The Addition is: ";
obj1 + obj2;
cout << "\n The Subtraction is: ";
obj1 ‒ obj2;
}
The
assignment operator can not be overloaded using friend function. Following are
the two reasons for that ‒
1.
The compiler is providing = operator
2.
The programmer is providing(overloading) = operator by friend function.
Due
to this ambiguity will be created and compiler will gives error.
1. Write the list of
rules for overloading operators with one example.
2. With suitable
example, explain how function overloading and operator overloading suports
compile‒time polymorphism.
3. What is operator
overloading? List out the rules to overload a binary operator.
Object Oriented Programming: Chapter 3: Inheritance and Compile Time Polymorphism : Tag: Oops, Computer Programming : C++ | Object Oriented Programming - Operator Overloading
Object Oriented Programming (OOPs)
CS25C07 2nd Semester CSE, CSE(CY) Depts | 2025 Regulation | 2nd Semester 2025 Regulation
English Essentials II
EN25C02 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation
Tamils and Technology தமிழர்களும் தொழில்நுட்பமும்
UC25H02 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation
Linear Algebra
MA25C02 2nd Semester | 2025 Regulation
Applied Physics (CSIE) II
PH25C03 2nd Semester AIDS, CSE, IT, CSE(CY) Dept | 2025 Regulation | 2nd Semester 2025 Regulation
Digital Principles and Computer Organization
CS25C06 2nd Semester AIDS, CSE, IT, CSE(CY) Dept | 2025 Regulation | 2nd Semester 2025 Regulation
Basic Electrical and Electronics Engineering
EE25C01 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation
Object Oriented Programming (OOPs)
CS25C07 2nd Semester CSE, CSE(CY) Depts | 2025 Regulation | 2nd Semester 2025 Regulation
Re-Engineering for Innovation
ME25C05 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation
Object Oriented Programming (OOPs) - Laboratory
CS25C07 2nd Semester CSE, CSE(CY) Depts | 2025 Regulation | 2nd Semester 2025 Regulation