KEMBAR78
7 Operator Overloading and Type Conversion | PDF | Computer Programming | Computing
0% found this document useful (0 votes)
7 views29 pages

7 Operator Overloading and Type Conversion

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views29 pages

7 Operator Overloading and Type Conversion

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Object Oriented Programming

Operator overloading
 Operator overloading means that the operation performed by the operator depends
on the type of the operands provided by the operator.
 In operator overloading an operator can be operated on user defined data types. i.e.
+ operator perform addition of integers or real numbers.
 C++ permit us to add two variables of user defined types with the same syntax that
is applied to basic types. This means that c++ has ability to provide the operators
with a special meaning for the data types. The mechanism of giving such special
meanings to an operator is known as operator overloading.
 We can overload all the c++ operators except the following:
o Operators which cannot be overloaded.
 Class member access operator (.).

 Scope resolution operator (: :).

 Size operator (sizeof).

 Conditional operator (? :).

Note:
When an operator is overloaded its original meaning is not lost. For example, the
operator +, which has been overloaded to add two user defined data type, can still be used
to add two integers.

Declaration and Definition of Operator Function:

Return_type operator op (arg_list); // declaration od operator function

Return_type class_name :: operator op(arg_list) //definition of Operator function.


{
Function body
}

Where,
 return_type is a type of value returned by the
specified operation.
 op is operator being overloaded.
 op is preceded by operator keyword.
Note:
 Operation function must be either member function or friend function.
 Difference between them,

Shri S.V,Patel College of CS & BM Page 1


Object Oriented Programming

o Friend function will have only one argument for unary operators and
two arguments for binary operators.
o A member function has no arguments for unary operators and one
argument for binary operators.
 This is because object is used to invoke a member function is
passed implicitly and therefore is available for the member
function.

Member Function Friend Function

Unary Operator No- argument One – argument


(That operate on one operand)

Binary Operator One- argument Two – arguments


(That operate on two operand)

The process for doing operator overloading:

 Create a class that defines the data type that is used in operator overloading
operation.
 Declare the operation function operator op () in public part of class. It may be
either member function or member function.
 Define the operation function to implement the function.

Unary Operator Overloading:


(Increment (++), Decrement (--) and unary (-) operator):
Unary operator using member function:

void operator ++ (); //declaration of ++ operator

void sample :: operator ++ () // definition of ++ operator


{
……………………
……………………
……………………
}

Shri S.V,Patel College of CS & BM Page 2


Object Oriented Programming

Overloaded unary operator function can be called by:

Syntax:
op x;
OR
x op;
Here x is an object and op is an operator which is overloaded.
Example:
++s1; OR s1++;

Example: (prog30. cpp )


#include<iostream.h>
#include<conio.h>
class sample
{
int x,y;
public:
void getdata()
{
cout<<"Enter the value of x";
cin>>x;
cout<<"Enter the value of y";
cin>>y;
}
void display()
{
cout<<"Value of x is"<<x<<"\n";
cout<<"Value of y is"<<y<<"\n";
}
void operator ++();

};
void sample :: operator ++()
{
x = x+1;
y = y+1;
}
void main()
{

Shri S.V,Patel College of CS & BM Page 3


Object Oriented Programming

clrscr();
sample s1;
sample s2;

s1.getdata();
s2.getdata();
++s1; //calling statement of operator ++
s2++;
cout<<"Object s1"<<"\n";
s1.display();

cout<<"Object s2"<<"\n";
s2.display();
getch();
}
Example: (prog31.cpp)
#include<iostream.h>
#include<conio.h>
class space
{
int x;
int y;
int z;
public:
void getdata(int a,int b, int c);
void display();
void operator -(); //declaration of unary - Operator
};
void space :: operator -()
{
x = -x;
y = -y;
z = -z;
}
void space::getdata(int a, int b, int c)
{
x=a;
y=b;
z=c;
}
void space::display()
{
cout<<"value of x is "<<x<<"\n";
cout<<"value of y is "<<y<<"\n";

Shri S.V,Patel College of CS & BM Page 4


Object Oriented Programming

cout<<"Value of z is "<<z<<"\n";
}
void main()
{
clrscr();
space s;
s.getdata(10,-20,30);
s.display();
-s;
cout<<"After calling unary - operator\n";
s.display();
getch();
}

Unary operator using friend function:


 It is possible to overload a unary operator using friend function as follows:

friend void operator ++ (sample &s); // declaration of operator function using friend

void operator ++ (sample &s) // definition of operator function


{
…………………………
…………………………
}

Here the argument is passed by reference. If we pass argument by value it will


not work because only a copy of the object is passed to operator ++ (). The changes
made inside the function will not affect in the called object.

Example: (prog32.cpp)
#include<iostream.h>
#include<conio.h>
class sample
{
int x,y;
public:
void getdata()
{
cout<<"Enter the value of x";
cin>>x;
cout<<"Enter the value of y";
cin>>y;
}

Shri S.V,Patel College of CS & BM Page 5


Object Oriented Programming

void display()
{
cout<<"Value of x is"<<x<<"\n";
cout<<"Value of y is"<<y<<"\n";
}
friend void operator ++(sample &s);

};
void operator ++(sample &s)
{
s.x = s.x+1;
s.y = s.y+1;
}
void main()
{
clrscr();
sample s1;
s1.getdata();
s1.display();

operator ++(s1); //calling statement

s1.display();
getch();
}

Example: (prog33.cpp)
#include<iostream.h>
#include<conio.h>
class space
{
int x;
int y;
int z;
public:
void getdata(int a,int b, int c);
void display();
friend void operator -(space &s);
};
void operator -(space &s)
{
s.x = -s.x;
s.y = -s.y;
s.z = -s.z;
}
Shri S.V,Patel College of CS & BM Page 6
Object Oriented Programming

void space::getdata(int a, int b, int c)


{
x=a;
y=b;
z=c;
}
void space::display()
{
cout<<"value of x is "<<x<<"\n";
cout<<"Value of y is "<<y<<"\n";
cout<<"value of z is "<<z<<"\n";
}
void main()
{
clrscr();
space s;
s.getdata(10,-20,30);
s.display();
operator -(s);//calling statement
cout<<"After calling unary operator\n";
s.display();
getch();
}

Summary:
Invoking (calling) statement for unary operators are:

Member function Friend function

Unary Operator ++s1; Operator ++(s1);


OR
s1++;

Here s1 is an object and ++ is an operator which is overloaded.

Binary Operator Overloading:


(Addition (+), subtraction (-), Multiplication (*) so on)
Binary operator using member function:
Program : (prog34.cpp)
#include<iostream.h>

Shri S.V,Patel College of CS & BM Page 7


Object Oriented Programming

#include<conio.h>
class complex
{
float x;
float y;
public:
complex()
{}
complex(float real, float imag)
{
x=real;
y=imag;
}
complex operator +(complex);
void display();
};
complex complex :: operator +(complex c)
{
complex temp;
temp.x = x +c.x;
temp.y = y + c.y;
return (temp);
}
void complex :: display()
{
cout<<x<<"\t"<<"and"<<"\t"<<y<<"\n";
}
void main()
{
complex c1,c2,c3;
c1=complex(2.5,3.5);
c2=complex(1.6,2.7);
c3 = c1+c2; //c3=c1.operator + (c2);

c1.display();
c2.display();
c3.display();
getch();
}

Note:
 Operator function receives only one argument explicitly.
 Operator function returns one object of class complex.
 Operator function is member function of class complex.

Shri S.V,Patel College of CS & BM Page 8


Object Oriented Programming

 While calling operator function c3=c1 +c2


 The object c1 takes responsibility of calling the operator function.
 Object c2 will pass as an argument to the operator function.
 C3=c1+c2 is equal to c3= c1.operator +(c2).
 So that data member of c1 are access directly in operator+ function and
data members of c2(that is pass as an argument) are accessed using the
dot operator.
Rule:
 In binary operator overloading left hand side operand is used to invoke the
operator function and right hand side operand is used to pass as an argument.

Binary operator using friend function:

Friend function may be used in the place of member functions for overloading
a binary operator. The only difference being that a friend function requires two
arguments to be passed to it, while a member function requires only one.

Invoking statement,

Result = obj1 + obj2;

Now is equivalent to:


Shri S.V,Patel College of CS & BM Page 9
Object Oriented Programming

Result = operator +(obj1, obj2);

But in some situation we would like to use friend function rather than member function.

Program: (prog35.cpp)
#include<iostream.h>
#include<conio.h>
class test
{
int p;
public:
void getdata()
{
cout<<"Enter value of p";
cin>>p;
}
void display()
{
cout<<"Value of p is"<<p;
}
friend test operator + (test t1, test t2);
};
test operator +(test t1, test t2)
{
test t3;
t3.p=t1.p + t2.p;
//cout<<"value of sum is"<<z;
return t3;
}
void main()
{
clrscr();
test t4,t5,t3;
t4.getdata();
t5.getdata();
t3= t4 + t5;
//t3=operator+(t4,t5);
t3.display();
getch();
}

Shri S.V,Patel College of CS & BM Page 10


Object Oriented Programming

Note:
There are certain situations where we would like to use friend
function instead of member function where we need to use two different types of
operands for binary operator, one object and other a built-in data.

A = B +2;
Where A and B are objects of a same class. This will work for a
member function but the statement,

A = 2 + B;
Will not work. This is because the left-hand operand which is responsible for invoking
the member functions. But friend function allows both approaches.

Calling statements:

Member function Friend function


Unary operator S++; operator ++(s1);
++S;
Binary operator c3=c1+c2; c3= operator +(c1,c2);

Rules for Operator Overloading:


1. Only existing operator can be overloaded. New operator cannot be overloaded.
2. We cannot change the basic meaning of an operator.
3. The overloaded operator must have one operand that is of object.
4. There are some operator which cannot be overloaded

Sizeof Size of operator


. Membership operator
:: Scope resolution operator
?: Conditional operator
.* Pointer to member operator
5. We cannot use friend functions to overload certain operator.
= Assignment operator
() Function call operator
[] Subscripting operator
-> Class member access operator

Shri S.V,Patel College of CS & BM Page 11


Object Oriented Programming

6. When using binary operators overloaded through a member function, the left hand
operand must be an object of the relevant class.
7. Unary operators, overloaded by means of a member function, take no argument
and return no explicit value, but, those overloaded by means of a friend function,
take one reference argument.
8. Binary operator overloaded through a member function take one explicit
argument and those which are overloaded through a friend function take two
explicit arguments.

Mathematical operation on string.

Example: (progr36.cpp)
#include<iostream.h>
#include<conio.h>
#include<process.h>
#include<string.h>

class string
{
char str[30];
public:
void getdata();
void display();
void operator +(string s);
void operator ==(string s);
void operator = (string s);
friend void operator <=(string s1, string s2);
};
void string :: getdata()
{
cout<<"Enter string\t";
cin>>str;
}
void string :: display()
{
cout<<"String is"<<"\t"<<str;
}
void string ::operator + (string s)
{
strcat(str, s.str);
cout<<"After concating string is\t"<<str;
}

Shri S.V,Patel College of CS & BM Page 12


Object Oriented Programming

void string :: operator ==(string s)


{
if(strcmp(str, s.str)==0)
cout<<"String is equal";
else
cout<<"String is not equal";
}
void string :: operator =(string s)
{
strcpy(str,s.str);
cout<<"After assignmnet string is"<<str;
}
void operator <=(string s1, string s2)
{
int m, n;
m = strlen(s1.str);
n = strlen(s2.str);
if (m < n || m == n)
cout<<s2.str<<"\t"<<"is greater Or Equal";
else
cout<<s1.str<<"\t"<<"is greater Or Equal";
}

void main()
{
clrscr();
int op,c,op1=1;
string a,b,d;

while (op1==1 && op!=5)


{
cout<<"\n\t 1. concatination";
cout<<"\n\t 2. equality";
cout<<"\n\t 3. asissignment";
cout<<"\n\t 4. Greater or equal";
cout<<"\n\t 5. Exit"<<"\n";

cout<<"Enter your choice";


cin>>op;

switch (op)
{
case 1:
cout<<"==Detail of string 1:=="<<"\n";
a.getdata();
Shri S.V,Patel College of CS & BM Page 13
Object Oriented Programming

cout<<"==Details of string 2:=="<<"\n";


b.getdata();

a+b;
break;
case 2:

cout<<"==Detail of string 1:=="<<"\n";


a.getdata();
cout<<"==Detail of string 2:=="<<"\n";
b.getdata();

a==b;
break;
case 3:
cout<<"==Detail of string 1:=="<<"\n";
b.getdata();
d=b;
break;

case 4:
cout<<"== details of strings"<<"\n";
a.getdata();
b.getdata();
operator <=(a,b);
break;
case 5:
exit(0);
default:
cout<<"Invalid choice";

}
}
getch();

Example: (prog43.cpp)
#include<iostream.h>
#include<conio.h>
#include<string.h>
class string
{
char *p;

Shri S.V,Patel College of CS & BM Page 14


Object Oriented Programming

int len;
public:
string()
{
len=0;
p=0;
}
string (char *s);
string (string &s);
~string()
{
delete p;
}
friend string operator+(string &s,string &t);
friend int operator<=(string &s,string &t);

friend void show(string s);


};

string :: string(char *s)


{
len = strlen(s);
p= new char[len+1];
strcpy(p,s);
}
string :: string(string &s)
{
len=s.len;
p=new char[len+1];
strcpy(p,s.p);
}
string operator+(string &s, string &t)
{
string temp;
temp.len=s.len +t.len;
temp.p= new char[temp.len+1];
strcpy(temp.p,s.p);
strcat(temp.p,t.p);
return (temp);
}
int operator <=(string &s, string &t)
{
int m= strlen(s.p);
int n=strlen(t.p);
if(m <= n)
Shri S.V,Patel College of CS & BM Page 15
Object Oriented Programming

return 1;
else
return 0;
}

void show(string s)
{
cout<<s.p;
}
int main()
{
clrscr();
string s1="new";
string s2="york";
string s3="Delhi";
string t1,t2,t3;

t1=s1;
t2=s2;
t3=s1+s3;

show(t1);
cout<<"\n";
show(t2);
cout<<"\n";
show(t3);
cout<<"\n";

if(t1 <= t3)


{
show(t1);
cout<<"\t smaller than\t";
show(t3);
cout<<"\n";
}
else
{
show(t3);
cout<<"\t smaller than\t";
show(t1);
cout<<"\n";

}
getch();
return 0;
Shri S.V,Patel College of CS & BM Page 16
Object Oriented Programming

Overload << and >> Operators:


Program: (prog37.cpp)
#include<iostream.h>
#include<conio.h>
const size=3;
class vector
{
int v[size];
public:
vector();
vector(int *x);
friend vector operator *(int a, vector b);
friend vector operator *(vector b, int a);
friend void operator >>(istream &, vector &);
friend ostream & operator <<(ostream &,vector &);

};
vector :: vector()
{
for(int i=0;i<size;i++)
{
v[i]=0;
}

}
vector :: vector(int *x)
{
for(int i=0;i<size;i++)
{
v[i]=x[i];
}
}
vector operator *(int a, vector b)
{
vector c;

for(int i=0;i<size;i++)
{
c.v[i] = a * b.v[i];

Shri S.V,Patel College of CS & BM Page 17


Object Oriented Programming

}
return c;
}
vector operator *(vector b,int a)
{
vector c;
for(int i=0;i<size;i++)
{
c.v[i] = b.v[i] * a;
}
return c;
}
void operator >>(istream &din, vector &b)
{
for(int i=0;i<size;i++)
{
din>>b.v[i];
}
// return(din);
}
ostream & operator <<(ostream &dout, vector &b)
{
for(int i=0;i<size;i++)
{
dout<<b.v[i]<<"\t"<<"\n";
}
return(dout);
}
int x[size]={2,4,6};
int main()
{
clrscr();
vector m;
vector n=x;
cout<<"Enter vector of m";
cin>>m;
cout<<"m is"<<m;

vector p,q;
p=2 * m;
q=n * 2;
cout<<"p ="<<p;
cout<<"q ="<<q;
getch();
Shri S.V,Patel College of CS & BM Page 18
Object Oriented Programming

return 0;
}

Type conversion
When constants and variables are of same type are mixed in one expression, automatic
conversion takes place.
Consider the statement,

s3 =s1 + s2;

When the objects are of same class type, the operations of addition and assignment are
carried out smoothly. Simply the values of all the data members of right-hand objects
are simply copied into the corresponding members of the object on left-hand.

What if one of the operands is an object and the other is a built in data type?

Different situations of data conversion between incompatible types.

1. Conversion from basic type to class type.


2. Conversion from class type to basic type.
3. Conversion from one class type to another class type.

Basic to class type:


The conversion from basic to class type is easily carried out. It is
automatically carried out by the compiler when we are using parameterized
constructor. In this type of the conversion, left-hand operand of = sign is always
class type and right-hand operand is always basic type.

Example1:
char *name1;
char *name2;
name1="Heta";
name2="Desai";
string s1=string(name1);
In this statement name1 from char* to string type and then assigns
the string type values to the object s1.

Example 2:
class time
{
int hour;
public:
......................

Shri S.V,Patel College of CS & BM Page 19


Object Oriented Programming

......................
time(int t)
{
t=1;
}
};
Void main()
{
……………..
……………...
time t1(a);
}

time t1(a);
After this statement hour member of t1 object will contain 1 as value.

Note:
The constructors used for the type conversion take a single argument where type is to be
converted.

Example: (prog38.cpp)
#include<iostream.h>
#include<conio.h>

class time
{
int hrs;
int mins;
public:
time()
{
hrs=0;
mins=0;

}
time(int t);
void display()
{
cout<<"Hours are: "<<hrs<<"\t"<<"mins are: "<<mins;
}
};

time :: time(int t)
{
hrs = t/60;
mins = t %60;

Shri S.V,Patel College of CS & BM Page 20


Object Oriented Programming

}
void main()
{
clrscr();
time t1;
int duration;
cout<<" enter duration ";
cin>>duration;
t1 = time(duration);
t1.display();

getch();
}

Class to Basic type:

The constructor functions do not support this type of conversion. C++ allows us
to define an overloaded casting operator that could be used to convert a class type data
to basic type. This type of casting function is referred as conversion function.
Syntax of an overloaded casting operator function:
Operator type_name()
{
//function statement
}
This function converts class type to basic type_name type.

Example:
Operator double()
{
……………
}
This operator function converts class object to type double.

Note:
Casting operator should follow following condition:
 Casting operator function must be a class member.
 It must not specify any return type.
 It must not have any argument.

Example: (prog39.cpp)
#include<iostream.h>
#include<conio.h>
class test
Shri S.V,Patel College of CS & BM Page 21
Object Oriented Programming

{
int value1;
float value2;

public:
void getdata()
{
cout<<"Enter value 1: ";
cin>>value1;
cout<<"Enter value 2: ";
cin>>value2;
}
void display()
{
cout<<"Value 1 is"<<value1<<"\n";
cout<<"Value 2 is"<<value2;

}
operator int()
{
return value1;
}
operator float()
{
return value2;
// cout<<"Value is"<<value2;
}
};

void main()
{
clrscr();
test t1;
t1.getdata();

int p;
float q;

p = t1;
q = t1;

cout<<"Value of p is: "<<p<<"\n";


cout<<"Value of q is: " <<q;
//t1.display();

Shri S.V,Patel College of CS & BM Page 22


Object Oriented Programming

getch();
}

Class to Class type:


Example:
Objx = objy;

 Objx is an object of class x and objy is an object of class Y. Class Y type


data is converted to the class X type and converted value is assign to the
objx.
 The conversion take place from class Y to class X, Y is known as source
class and class X is known as Destination class.
 Conversion between objects can be carried out either by constructor or
casting function.
 In case of conversion between objects, typename refers to the destination
class. So when a class needs to be converted, a casting operator function
can be used in source class.
 When a class needs to be converted, a casting operator function can be used
in source class. The conversion take place in source class and the result is
given to the destination class object.

Type conversion:

Conversion Source class Destination class


Basic -> class Not applicable Constructor

Shri S.V,Patel College of CS & BM Page 23


Object Oriented Programming

Class -> Basic Casting operator Not applicable


Class -> class Casting Operator Constructor

Example: (prog55.cpp)
#include<iostream.h>
#include<conio.h>
class cm
{
int c;
public:
cm()
{
}
cm(int c1)
{
c=c1;
}
void show()
{
cout<<"Equal to cm\t"<<c;
}
};
class meter
{
float m;
public:
void getdata()
{
cout<<"Enter meter\t";
cin>>m;
}
operator cm()
{
return (m*100);
}
};
int main()
{
meter m;
cm c;
m.getdata();
c = m;
Shri S.V,Patel College of CS & BM Page 24
Object Oriented Programming

c.show();
getch();
return 0;
}

Example: (prog40.cpp)
#include<iostream.h>
#include<conio.h>

class dollar
{
private:
float d_value;
public:
dollar()
{
d_value=0.0;

}
dollar(float d)
{
d_value = d;
}
void show()
{
cout<<"Vslue of dollar is"<<d_value;
}
};
class rupee
{
float r_value;
public:
void getdata()
{
cout<<"Enter the rupee";
cin>>r_value;
}
void show()
{
cout<<"Rupee value is"<<r_value;
}
operator dollar()
{
return (r_value/60);

Shri S.V,Patel College of CS & BM Page 25


Object Oriented Programming

}
};
void main()
{
clrscr();
dollar d1;
rupee r1;
r1.getdata();
d1 = r1;
d1.show();
getch();

Example: (prog41.cpp)
#include<iostream.h>
#include<conio.h>
class invent2;
class invent1
{
int code;
int items;
float price;
public:
invent1(int a, int b,float c)
{
code=a;
items=b;
price=c;
}
void putdata()
{
cout<<"Code: "<<code<<"\n";
cout<<"Items: "<<items<<"\n";
cout<<"Price: "<<price<<"\n";
}
int getcode()
{
return code;
}
int getitems()
{
return items;
}

Shri S.V,Patel College of CS & BM Page 26


Object Oriented Programming

float getprice()
{
return price;
}
operator float()
{
return(items*price);
}

};
class invent2
{
int code;
float value;
public:
invent2()
{
code=0;
value=0;
}
invent2(int x, float y)
{
code=x;
value=y;
}
void putdata()
{
cout<<"Code: "<<code<<"\n";
cout<<"Value: "<<value<<"\n";
}
invent2(invent1 p)
{
code=p.getcode();
value=p.getitems()*p.getprice();
}
};

int main()
{
clrscr();
invent1 s1(100,5,140.0);
invent2 d1;

float total_value;

Shri S.V,Patel College of CS & BM Page 27


Object Oriented Programming

total_value=s1; //object to basic type conversion

d1 = s1; // convert from invent1 to invent2


s1.putdata();
cout<<"Total value is: "<<total_value<<"\n";
d1.putdata();
getch();
return 0;
}
Note:
 Operator float() function is used to convert invent1 type data to a float.
 The constructor invent2 (invent1) is used to convert the invent1 type data to the
invent1 type data and constructor used in invent2 class.

Example: (prog42.cpp)
Write a program to convert time 24 format to time 12 format using class to class
conversion.
#include<iostream.h>
#include<conio.h>
class time24
{
int hour,min;
public:
time24()
{
hour=0;
min=0;

}
void getdata()
{
cout<<"Enter the value of hour and min in 24 hour format";
cin>>hour;
cin>>min;

}
int get_hour()
{
return hour;
}
int get_min()
{
return min;
Shri S.V,Patel College of CS & BM Page 28
Object Oriented Programming

}
};
class time12
{
int hour,min;
public:
time12()
{
hour=0;
min=0;

}
time12(int h,int m)
{
hour=h;
min=m;
}
time12(time24 t)
{
hour=t.get_hour();
// min=t.get_min();
if(hour>12)
{
hour=hour%12;
min=t.get_min();
}
}
void display()
{
cout<<hour<<" : "<<min;
}
};
int main()
{
clrscr();
time24 t24;
t24.getdata();
time12 t12;
t12=t24;
t12.display();
getch();
return 0;
}

Shri S.V,Patel College of CS & BM Page 29

You might also like