0% found this document useful (0 votes)
36 views

Unit3 - Operator Overloading and Type Conversion

The document discusses operator overloading in C++. It allows giving special meanings to operators like + when used with user-defined types, to extend functionality. It explains how to overload operators as member or friend functions by defining special operator functions. Examples demonstrate overloading operators like increment, subtraction, addition to work with user-defined types.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Unit3 - Operator Overloading and Type Conversion

The document discusses operator overloading in C++. It allows giving special meanings to operators like + when used with user-defined types, to extend functionality. It explains how to overload operators as member or friend functions by defining special operator functions. Examples demonstrate overloading operators like increment, subtraction, addition to work with user-defined types.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Operator overloading and type conversion

C++ tries to use the user defined data types much in the way, the built in data types are
used. C++ has the ability to add special features to the functionality and behaviour of
already existing operators like arithmetic operators. The mechanism of giving special
meaning to an operator is known as operator overloading. In C++ one can overload any valid
operator of C++ except the following:
Ø Class member access operator ( . ) (dot)
Ø Class member access operator when pointer is used ( .* )
Ø Scope resolution operator ( :: )
Ø sizeof operator
Ø Conditional operator ( ? : )
Operator overloading is used to make most of the standard operators (available for built in
data types) to be used with user defined data type items.
v Operator overloading is applicable only to the existing operators, no new operator
can be created using operator overloading.
v The overloaded operator must use at least one user defined data type.
v Through operator overloading semantics of an operator can be enhanced but the
syntax, the general grammar like number of operands, precedence and associativity
remains the same.
v Hence when an operator is overloaded, its original meaning is never lost. for
example if + is used to find sum of integers or floats, then it can only be used to find
sum but after overloading + can be redefined to find sum of objects or to
concatenate strings but not to subtract numbers.
v However either a friend or a member function can be used to overload the
operators, some of the operators like = , ( ) , [ ] and -> cannot be overloaded by
using fried function.
v Binary operators + , - , * , / must return a relevant value.

Syntax for operator overloading


Operator overloading is implemented through a special member function known as
operator function. Syntax for defining an operator function, when it is a member function of
the class:
Return_type class_name :: operator op_symbol (arguments list )
{
................Function body..............
}
Ø Here return_type is return type of function.
Ø 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;
}
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;
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 */
#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;
}
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 time operator+(time); friend time operator + (time, time);


operator
overloading
function
time time::operator+(time t) time operator + (time t1, time t2)
Definition of { {
operator time temp; time temp;
overloading int m = mins + t.mins; int m = t1.mins + t2.mins;
function temp.mins = m % 60; temp.mins = m % 60;
temp.hours=hours+t.hours+ temp.hours=t1.hours+t2.hours+m
m/60; /60;
return temp; 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 ==


{ function as friend to class
//... as defined in above program.... time
friend bool operator == (time t1, time t2)
};

bool operator ==(time t1, time t2) Define the operator


{ overloading function
return (ti.hours == t2.hours && t1.mins == t2.mins);
}

if ( t1 == t2 ) Now, == operator can be


cout<<”\n both time values are equal to each other “; used in main program to
compare two objects

Type conversions in C++


Type conversion is the process of converting one type of expression or item into another
type. Type conversion can be implicit or explicit

Implicit / Automatic type conversion


Implicit type conversion is applied when data items of different types are intermixed in an
expression. This type of conversion is performed by the compiler itself so that no loss of
data or information takes place. C++ compiler converts all items of expression into the
largest data type present into the expression.
v For example, if an expression contains items of the types like float, double and long
double, compiler will implicitly convert all types to long double.
v Unsigned long integer is the longest integer data type, hence if one item in the
expression is of the type unsigned long integer, then all int and short data type items
will get implicitly converted into long integer data type.
An example to demonstrate implicit type conversion
If following are the items:
char choice; int numi; float numf; double numdb; long double numld;
Then implicit conversion for an expression given below will be like:
value = (choice / numi) + ( numf * numdb) - (numf + numi) + (numld / numf)

int double float long-double

long-double
double

long-double

The expression will give result in long double type after implicit conversions.

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)
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


operator type_name ( ) • It must be a class member
{ .......... • It must not have a return type but a return
.......... statement
function body • 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
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;
}
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();
}
}; // 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();
}

You might also like