2. Ø The declaration and definition statement of operator overloading function must
have keyword operator.
Ø op_symbol is any valid operator symbol of C++ which can be overloaded.
Ø Operator overloading function can be a member function or a friend function.
v Friend function – if the operator overloading function is a friend function,
then it will be called without any object, hence the number of operands
required for the operator (to be overloaded) are to be passed as arguments
to the function. For example to overload unary minus (-) there will be one
argument to the function and to overload plus ( + ) two arguments will be
required.
v Member function - if the operator overloading function is a member function
of the class, then it will be called using object of that class. The object used to
invoke the member function is implicitly passed to the function, by the
compiler and hence that is made available in the member function directly.
So every time this function will be called the compiler will have one active
object, whose data members can be used directly. Therefore the number of
arguments in the operator overloading function will be one less than actually
required. For example to overload unary minus (-) there will be no argument
to the function and to overload plus ( + ) only one argument will be passed to
the operator overloading function.
Steps of operator overloading
Ø Create the class whose objects are to be used in operator overloading.
Ø Declare and define the operator overloading function which can either be a public
member function of the class or a friend function to the class.
Program 1: operator overloading of increment (unary) operator ++ using
member function.
/* program to increase the private data items of an object by
10 each. */
#include <iostream>
using namespace std;
class fruit
{
int bananas, mangoes;
public:
fruit ( int b, int m) // constructor
{ bananas = b;
mangoes = m;
}
void display( )
{
cout<<”n number of bananas : “<< bananas;
cout<<”n number of mangoes : “<< mangoes;
3. }
void operator ++( ); // operator overloading
// using member function
};
void fruit::operator ++( ) /* member function to overload
unary operator does not accept any argument */
{
bananas = bananas + 10;
manges = mangoes + 10;
}
int main( )
{
fruit basket1(5,9) , basket2(15, 5);
cout<<”n ...... initially no of fruits in
baskets.........”;
basket1.display( );
basket2.display( );
++basket1;
++basket2;
cout<<”n after using overloaded increment ++ operator
with objects ”;
basket1.display( );
basket2.display( );
return 0;
}
Output:
...... initially no of fruits in baskets.........
number of bananas : 5
number of mangoes : 9
number of bananas : 15
number of mangoes : 5
after using overloaded increment ++ operator with objects
number of bananas : 15
number of mangoes : 19
number of bananas : 25
number of mangoes : 15
Program 2: operator overloading of unary minus ( - ) using friend function
//to find negative of a complex number, using friend function
#include<iostream>
using namespace std;
class complex
{
int real, img;
4. public:
complex( ) { } // default constructor
complex (int n) // constructor with one parameter
{ real = img = n; }
complex (int r, int i) //constructor with two parameters
{ real = r;
img = i;
}
void display( )
{ cout<<”n complex number = “<< real<<” +
“<<img” i”; }
friend complex operator – (complex c)
}; // end of class
complex operator – (complex c) // operator function
{
c.real = - c.real;
c.img = - c.img;
return c;
}
int main ( )
{
complex num1(5, 8), num2;
cout<<”n original complex number......................”;
num1.display( );
num2 = - num1; // calling operator function
cout<<”n negative complex umber.......................”;
num2.display( );
return 0;
}
Output:
original complex number......................
complex number = 5 + 8 i
negative complex number.......................
complex number = - 5 + -8 i
Program 3: overloading arithmetic operator ( + ) to find sum of two objects
(using member function to overload + )
/* program to overload + operator to find sum of two time
values given in hours and minutes */
5. #include<iostream>
using namespace std;
class time
{
int hours, mins;
public:
time() // default constructor
{ hours = mins = 0; }
time( int x, int y ) // parameterised constructor
{ hours = x;
Mins = y;
}
void show() // member function shows time
{
cout<<”n time = “<<hours <<":"<< mins;
}
//overloading '+' operator using member function.
time operator+(time); // operator function
};
/*operator function to overloading '+' operator using
member function defined outside the class */
time time::operator+(time t)
{
time temp;
int m = mins + t.mins;
temp.mins = m % 60;
temp.hours = hours + t.hours + m / 60;
return temp;
}
void main()
{
clrscr();
time t1(5,45), t2(2,30), t3;
t3 = t1 + t2; //operator function called – see note
t1.show();
t2.show();
cout<<"n Sum of times ";
t3.show();
return 0;
}
6. Output:
time = 5 : 45
time = 2 : 30
Sum of times
time = 8 : 15
Explanation:
In the statement t3 = t1 + t2;
v t3 stores the value of object returned by operator overloading function.
v Because operator +( ) function is a member function, it can only be invoked by using
an object of the same class. t1 is the object which has the responsibility of invoking
the operator function. Hence data items of t1 are accessed directly in operator
function.
v The operator+( ) function accepts one argument of type class time. t2 is accepted by
the function as actual parameter.
Overloading + operator using friend function
With the following changes, above operator overloading which is done by using member
function, can also be done by using friend function.
Using member function
Using friend function
Declaration of
operator
overloading
function
time operator+(time); friend time operator + (time, time);
Definition of
operator
overloading
function
time time::operator+(time t)
{
time temp;
int m = mins + t.mins;
temp.mins = m % 60;
temp.hours=hours+t.hours+
m/60;
return temp;
}
time operator + (time t1, time t2)
{
time temp;
int m = t1.mins + t2.mins;
temp.mins = m % 60;
temp.hours=t1.hours+t2.hours+m
/60;
return temp;
}
Example 4: overloading relation operator equal to ( == ) to compare private
data items of two objects.
Following friend function can be used to overload == operator to compare two time values.
This function can be added in proper sequence in the above program.
class time Declare the operator ==
8. Explicit type conversion / type casting
Explicit type conversion is also known as type casting and it is implemented by using
following syntax
(data_type) expression;
For example if there are variables like
int m = 35; int n = 6; float x;
x = m / n; //here m =35, n = 6 so x = 5.0
x = (float) m / (float) n // here m = 35.0, n=6.0 so x = 5.8333
Conversion between basic and user defined data types
The conversions discussed above do not require special code, as only built in data types are
used for conversion. Special programming is needed for conversion between user defined
data items and basic data type, because compiler need to understand the structure and
memory requirement of user defined data type before conversion. Different types of
conversion are
§ Basic to user defined data type (class)
§ User defined (class) to basic data type
§ One user defined (class1) to another user defined data type (class2)
value = (choice / numi) + ( numf * numdb) - (numf + numi) + (numld / numf)
int double float long-double
double
long-double
long-double
The expression will give result in long double type after implicit conversions.
9. Conversion from basic data type to class type
Conversion from basic data type to class type can be performed by using a single parameter
in a constructor. The example below will explain it in detail
Program 1: to demonstrate basic to class data type using constructor
// program to convert quantity of weight into kilograms and
grams
#include<iostream>
class weight
{
int kg, gm;
public:
weight ()
{ kg = gm = 0; }
weight ( int w ) // this constructor will
convert an integer to class type
{
kg = w / 1000;
gm = w % 1000;
}
void display ( )
{ cout<<”n kg = “<< kg<<”t gm = “<<gm ; }
}; // end of class
int main ( )
{
int wgm;
cout<<”n enter weight in grams : “;
cin>> wgm;
weight mangoes ;
mangoes = wgm; // wgm gets converted into kg
and gm
magoes.display ( );
return 0;
}
Output:
enter weight in grams : 4520
kg = 4 gm = 520
Conversion from class type to basic type
C++ has the option of overloading casting operator which can be used for conversion from
class to basic type. The function used to overload casting operator is usually called
conversion function.
Syntax of conversion function Rules to define conversion function
10. operator type_name ( )
{ ..........
..........
function body
..........
...........
}
• It must be a class member
• It must not have a return type but a return
statement
• Conversion function cannot accept any
argument
• Being a member function, it is invoked by an
object and values of that object are used inside
the function. Hence no argument is passed to
conversion function.
Program 3: demonstration of conversion function to convert from class to basic type
// program to convert weight in kilograms and grams to grams
only (class to basic type)
#include<iostream>
class weight
{
int kg, gm;
public:
weight ()
{ kg = gm = 0; }
weight ( int k, int g )
{
kg = k ;
gm = g ;
}
operator int ( ) // conversion function
{
int w ;
w = (kg * 1000) + gm;
return ( w );
}
void display ( )
{ cout<<”n weight in kg & gm : “<< kg<<” kg
“<<gm << “ gm “; }
}; // end of class
int main ( )
{
int wfruits , wvegies ;
weight fruits(3 , 500 );
weight vegies( 2 , 250 );
fruits.display ( );
vegies.display ( );
wfruits = fruits ; // invokes operator function
11. and return weight in grams
wvegies = vegies; // invokes operator function ,
behaves as vegies.opertor int ()
int total_weight = wfruits + wvegies;
cout<<”n total weight of fruits and vegetables : “<<
total_weight;
return 0;
}
Output:
weight in kg & gm : 3 kg 500 gm
weight in kg & gm : 2 kg 250 gm
total weight of fruits and vegetables : 5750
One class type to another class type
Conversions from one class to another class type can be carried out either by a constructor
or by a conversion function.
If objA is object of class A and objB is the object of class B. To convert class B data type to
class A data type following statement can help
objA = objB ;
For this conversion, class B is known as source class and class A is known as destination
class.
When a class is to be converted, casting operator function can be used in source class.
operator type_name ( )
To convert source class type data item to destination class type data item, above function
should be a member function of the source class and type_name should be the type of
destination class.
Program 4: to demonstrate the conversion from one class to another
// program to illustrate class to basic and class to class
conversions
# include <iostream.h>
class one
{
int code,items;
float price;
public:
one(int c,int i,int p)
{
code = c;
items = i;
price = p;
12. }
void showdata()
{
cout<<"n CODE= "<<code;
cout<<"n ITEMS= "<<items;
cout<<"n VALUE= "<<price;
}
int getcode()
{
return code;
}
int getitems()
{
return items;
}
int getprice()
{
return price;
}
Operator float () // class to basic
conversion, returns float value
{
return items*price;
}
}; // end of class one
class two
{
int code;
float value;
public:
two()
{
code = 0;
value = 0;
}
two(int x,float y)
{
code = x;
value = y;
}
void showdata()
{
cout<<"n CODE= "<<code;
cout<<"n VALUE= "<<value;
}
two(one obj1)
{
Code = obj1.getcode();
Value = obj1.getitems()*obj1.getprice();
}
13. }; // end of class two
main()
{
one ob1(1000,20,150);
float tot_value;
two ob2;
tot_value=ob1; // invokes operator function of class
one
ob2 = one( ob1); // conversion from class two to class
one
cout<<"n item from class one ";
ob1.showdata();
cout<<"n VALUE= "<<tot_value;
cout<<"item from class two ";
ob2.putdata();
}