Anda di halaman 1dari 27

BCA-III C++ and Object Oriented Programming

CHAP-6 OPERATOR OVERLOADING and TYPE CONVERSION

CONCEPT OF OPERATOR OVERLOADING

We know that operators such are +, -, *, /, <=, >= are work with a built in data type (int,
float, double), but these operators are not work directly with user defined data types
(objects).
For example, suppose a, b and c are built in data types like int and float, and if we are
doing c = a + b ; then it works perfectly. But if when a, b and c are objects of a user
defined class then it will gives errors when compile.
So using overloading an operator, you can make above statements valid even if a, b and c
are objects (user defined).
So the term operator overloading refers to giving the basic C++ operators provide
additional or special meanings when they are applied to user defined data types.
So, the mechanism of giving such special meaning to an operator is known is known as
operator overloading.
The operator overloading can be defined using special function, called operator function.
The general form (or syntax) of an operator functions are,

Operator Function Inside the Class:


return-type operator OP(argument list)
{
Function body ;
}
Operator Function Outside the Class:
return-type class-name :: operator OP(argument list)
{
Function body ;
}

In above syntax, the return type is the type of value returned by this operator function, the
operator is a keyword for defining operator function. The OP is an operator (+, - *, <, >)
being overloaded.

Prepared by | Hemang R. Chath


BCA-III C++ and Object Oriented Programming
RULES FOR OPERATOR OVERLOADING

The rules for overloading operators are as follows:

1. An operator function can be either a non static member function or a non member
function with at least on parameter that has class, reference to class, enumeration or
reference to enumeration type.
2. You cannot change the precedence, or the number of operands of an operator.
3. An overloaded operator cannot have default arguments in the argument list.
4. Only existing operators can be overloaded, new operators cannot be created.
5. We cannot change the basic meaning of an operator, it means we cannot redefine the plus
(+) operator to subtract one value from other.
6. In case of unary operators member functions have no arguments and for Binary operators
member function have one argument.
7. In case of unary operator friend function have one argument and for Binary operators
friend function have two arguments.
8. The binary arithmetic operators such are +, -, * must be return a value.
9. There are some operators that cannot be overloaded such are,

sizeof : size of operator


. : dot operator
.* : pointer to member operator
:: : scope resolution operator
? : Conditional operator
10. The following operators in which we cannot use friend function for writing a operator
function,

= : Assignment operator
() : function call operator
[] : subscripting operator
-> : class member access operator

Prepared by | Hemang R. Chath


BCA-III C++ and Object Oriented Programming
OVERLOADING UNARY and BINARY OPERATORs

OVERLOADING UNARY OPERATORs

An operator which work with only single operand is called unary operators, such are +, -,
++, -- operators.
Let us consider to overload increment operator ++, which will increment value of object
in same way of basic data type.

Example 1 (To overload Unary Operator ++)

#include<iostream.h>
#include<conio.h>
class test
{
int x;
public:
test()
{
x=0;
}
void operator ++() // ++ operator function
{
++x;
}
void show()
{
cout << "The value is: " << x << endl ;
}
};
main()
{
clrscr();
test t1,t2;
++t1; // call operator function for t1 object
t1.show();
++t2; // call operator function for t2 object
++t2;
++t2;
t2.show();
getch();
return 0;
}

Prepared by | Hemang R. Chath


BCA-III C++ and Object Oriented Programming
Output:
The value is: 1
The value is: 3

In above program, the operator function ++ is a member function, so it has no argument,


and it will call by increment objects.
In above program when we write ++t1 in main ( ) function then it will call operator
function void operator ++ ( ), which will increment the data x of the object t1.
Then further we write ++t2 three times, which call operator function void operator ++( )
three times, so increment the value of x of t2 three times.
So from above program, using operator function we will use ++ operator for user defined
type same way as inbuilt data type.

Example 2 (To overload an Unary ++ Operator, which will return value form the
operator function)

#include<iostream.h>
#include<conio.h>
class test
{
int x;
public:
test()
{
x=0;
}
void show()
{
cout << "The value is: " << x << endl;
}
test operator ++() // ++ operator function with
// return type
{
test temp;
temp.x = ++x;
return temp;
}
};

Prepared by | Hemang R. Chath


BCA-III C++ and Object Oriented Programming
main()
{
clrscr();
test t1,t2;
t2=++t1; // call operator function ++
t1.show();
t2.show();
getch();
return 0;
}

Output:
The value is: 1
The value is: 1

Example 3 (To overload an Unary [minus] Operator )

#include<iostream.h>
#include<conio.h>
class A
{
int x,y,z;
public:
void getdata(int a, int b, int c)
{
x=a;
y=b;
z=c;
}
void operator -() // - operator function
{
x = -x;
y = -y;
z = -z;
}
void show()
{
cout<<x<<" "<<y<<" "<<z << endl;
}
};

Prepared by | Hemang R. Chath


BCA-III C++ and Object Oriented Programming
void main()
{
clrscr();
A a1;
cout<<"Original values are: "<< endl;
a1.getdata(10,-20,30);
a1.show();
-a1; // call (minus) operator
cout<<"After invoke - operator values are: "<<endl;
a1.show();
getch();
}

Output:
Original values are:
10 -20 30
After invoke operator values are:
-10 20 -30

OVERLOADING BINARY OPERATORs

An operator which work with two operands are called binary operators, such are +, -, *,
= =, >=, etc.
Let us consider to overload binary + operator, which will doing addition of two objects
object1 + object2 in same way of basic data types such as a + b.

Example 1 (To overload Binary + Operator to perform the operation Obj1 + Obj2)

#include<iostream.h>
#include<conio.h>
class test
{
int x;
public:
void getdata()
{
cout<<"Enter Value: ";
cin>>x;
}

Prepared by | Hemang R. Chath


BCA-III C++ and Object Oriented Programming
void operator +(test p) // For Binary Operator
// use one argument
{
x = x + p.x; // p is a dummy object of t2
}
void show()
{
cout<<"The sum of value is: = " << x <<endl;
}
};
void main()
{
clrscr();
test t1,t2;
t1.getdata();
t2.getdata();
t1 + t2 ; // call binary + operator and
// store value in object t1
t1.show();
getch();
}
Output:
Enter Value: 5
Enter Value: 6
The sum of value is: = 11

In above program, if we write the statement t1 + t2 in the main ( ) function, then it will
call the operator function void operator + (test p) and perform the addition of two
objects values and stores in the t1 object.
So t1 + t2 is same as the t1 = t1 + t2.

Prepared by | Hemang R. Chath


BCA-III C++ and Object Oriented Programming
Example 2 (To overload Binary + Operator to perform the operation Obj3 = Obj1 +

Obj2 )

#include<iostream.h>
#include<conio.h>

class test
{
int x;
public:
void getdata()
{
cout << "Enter Value: " ;
cin >> x ;
}

test operator +(test p) //For binary operator use 1 argument


{ // return type is object type
test temp ;
temp.x = x + p.x ;
return temp ;
}

void show()
{
cout<<"The sum of value is: = "<<x<<endl;
}

};

void main()
{
clrscr();

test t1,t2,t3 ;

t1.getdata();
t2.getdata();

t3 = t1 + t2 ; // call Binary + operator function

t3.show();
getch();
}

Prepared by | Hemang R. Chath


BCA-III C++ and Object Oriented Programming
Output:
Enter Value: 6
Enter Value: 9
sum of value is: = 15

Example 3 (To overload Binary + Operator to perform the following operation

Obj5 = Obj1 + Obj2 Obj3 + Obj4)

#include<iostream.h>
#include<conio.h>

class test
{
int x;
public:
test() // default constructor
{
x=0;
}
test(int a) // parameterized constructor
{

x=a;
}
test operator + (test p) // + operator function
{
test temp1;
temp1.x = x + p.x;
return temp1;
}
test operator - (test q) // - Operator function
{
test temp2;
temp2.x = x - q.x;
return temp2;
}
void show()
{
cout<<"Value is: "<<x<<endl;
}

};

Prepared by | Hemang R. Chath


BCA-III C++ and Object Oriented Programming
void main()
{
clrscr();
test t1(5),t2(4),t3(3),t4(2),t5;
t5 = t1 + t2 - t3 + t4;// call + & - operator function
t1.show();
t2.show();
t3.show();
t4.show();
cout << "Answer of " << endl ;
t5.show();
getch();

Output:
Value is: 5
Value is: 4
Value is: 3
Value is: 2
Answer of Value is: 8

Prepared by | Hemang R. Chath


BCA-III C++ and Object Oriented Programming
OVERLOADING OPERATORs USING FRIEND FUNCTION

In case of Unary Operators such are (+, -, ++, --), friend function have one argument and
for Binary operator such are (+, -, *, = =), friend function have two arguments
Let us see the example of overload binary + operator using friend function.

Example (To overload Binary + Operator using Friend Function to perform the

operation Obj3 = Obj1 + Obj2)

#include<iostream.h>
#include<conio.h>

class test
{
int x;
public:
void getdata()
{
cout << "Enter Value: " ;
cin >> x ;
}

friend test operator + (test, test) ;

void show()
{
cout<<"The sum of value is: = "<<x<<endl;
}

};
test operator +(test p, test q)//For binary operator
//friend function use 2 arguments
{
test temp ;
temp.x = p.x + q.x ;
return temp ;
}

void main()
{
clrscr();

Prepared by | Hemang R. Chath


BCA-III C++ and Object Oriented Programming
test t1,t2,t3 ;

t1.getdata();
t2.getdata();

t3 = t1 + t2 ; // call Binary + operator function

t3.show();

getch();
}

Output:
Enter Value: 9
Enter Value: 3
The sum of value is: = 12

In the above program, we use friend function, so an operator function has two arguments
which are object type and return type is also object type.
In operator function we define three objects p, q and temp which are dummy object
parameters of actual object parameter t1, t2 and t3.
The operator function returns a value to the object t3.

Prepared by | Hemang R. Chath


BCA-III C++ and Object Oriented Programming
MANIPULATION OF STRING USING OPERATORs

We know that string is nothing but a character array, it contains number of characters.
Basic string manipulation operations are:
1. String Concatenation (Combine two string together)
2. String Comparison
We can perform operation like c = a + b if a, b and c are built in data types like integer
type. But if the data type is string and we are doing same operation then compiler gives
error.
It is not possible two add two string, but if we define user defined data type (objects) and
use the concept of operator overloading and perform same operation, it will gives the
result which will combined two string together.
The string manipulation operation performed by using new operator which will save the
space for entering exact characters in the character string.

Example 1 (To overload binary + operator to perform following operation,

String3 = String1 + String2 using operator overloading)

#include<iostream.h>
#include<conio.h>
#include<string.h>
class string
{
char *s;
int len;
public:
string() // default constructor for null string
{
s="";
len=0;
}
string (char *s1)
{
len = strlen(s1);
s = new char[len+1]; // provide exact location
// to string s
strcpy(s,s1);
}

Prepared by | Hemang R. Chath


BCA-III C++ and Object Oriented Programming
string (int a)
{
len = a;
s = new char [len + 1] ;
}
string operator + (string s5)
{
len = strlen(s) + strlen(s5.s) ;
string temp(len);
strcpy(temp.s,s);
strcat(temp.s,s5.s);
return temp;
}
void show()
{
cout<<"String is: "<<s<<endl;
}
};
main()
{
clrscr();
string str1 = "Comp";
string str2 = "uter" ;
string str3;
str1.show();
str2.show();
str3 = str1 + str2 ; // call + operator function
str3.show(); // show combined string
getch();
return 0;
}

Output:
String is: Comp
String is: uter
String is: Computer

Prepared by | Hemang R. Chath


BCA-III C++ and Object Oriented Programming
Example 2 (To overload Binary >= Operator for string to perform the string

comparison for two objects using operator overloading)

#include<iostream.h>
#include<conio.h>
#include<string.h>
class string
{
char *s;
int len;
public:
string() // default constructor for null string
{
s="";
len=0;
}
string (char *s1)
{
len = strlen(s1);
s = new char[len+1]; // provide exact location
// to string s
strcpy(s,s1);
}
int operator >= (string s5)
{
int a = strlen(s) ;
int b = strlen(s5.s) ;
if (a >= b)
return (1);
else
return (0);
}
void show()
{
cout<<"String is: "<<s<<endl;
}
};
main()
{
clrscr();
string str1 = "Computer";
string str2 = "Application" ;

Prepared by | Hemang R. Chath


BCA-III C++ and Object Oriented Programming
str1.show();
str2.show();
if (str1 >= str2)
cout<<"String 1 is greater than string 2";
else
cout<<"String 1 is less than string 2";
getch();
return 0;
}

Output:
String is: Computer
String is: Application
String 1 is less than string 2

Example 3 (To Overload Binary = = Operator for sting to perform the string

comparison for two objects using operator overloading)

#include<iostream.h>
#include<conio.h>
#include<string.h>

class string
{
char *s;
int len;

public:
string() // default constructor for null string
{
s="";
len=0;
}
string (char *s1)
{
len = strlen(s1);
s = new char[len+1]; // provide exact location
// to string s
strcpy(s,s1);
}

Prepared by | Hemang R. Chath


BCA-III C++ and Object Oriented Programming
int operator == (string s5)
{

if (strcmp(s,s5.s)==0)
return 1;
else
return 0;
}
void show()
{
cout<<"String is: "<<s<<endl;
}
};
main()
{
clrscr();
string str1 = "Computer";
string str2 = "Computer" ;
str1.show();
str2.show();
if(str1 == str2)
cout<<"String 1 is equal to String 2";
else
cout<<"String 1 is not equal to String 2";
getch();
return 0;
}

Output:
String is: Computer
String is: Computer
String 1 is equal to String 2

Prepared by | Hemang R. Chath


BCA-III C++ and Object Oriented Programming
TYPE CONVERSIONS (DATA CONVERSION)

We know that the = operator assign the value from one variable from right side to another
on left side in a statement, for example
int a, b ;
a = b ;
If the variables are built in data type then no problem, compilers cant give any errors.
In case of class objects, the value of all the data members of the right hand objects are
simply copied into the corresponding members of the objects on the left side.
For example, a class student has two objects s1 and s2, and it have two data members
name and age.
Then we write a statement s1 = s2 ; the value of two data members of the right hand
objects s2 are simply copied into members of the objects on the left hand s1. This
operation is possible only if two objects are same class.
But if one operand (variable) is object type and another operand is built in type variable?
or if they are object of different class then compilers complaints and give errors and
above operation are not possible.
So, for user defined data types do not support automatic type conversion, compiler
complains errors, so a conversion routine must be design for such type of operation.
Three types of situation may be arise in the data conversion, the compiler does not
compile, so we must be write a routine or operator function to perform these operation.
The situation was:

1. Conversion from Basic (buit in) type to Class (object) type


2. Conversion from Class (object) type to Basic (built in) type
3. Conversion from one Class (object) to another Class (object) type

Suppose s1 is an object of class student, s2 is an object of class test and m is integer


variable,

int m ; // built in data type variable

student s1 ; // object of class student

test s2 ; // object of class test

Prepared by | Hemang R. Chath


BCA-III C++ and Object Oriented Programming
Then we cannot write s1 = m ; // Basic to Class type Conversion

m = s1 ; // Class to Basic type Conversion

s1 = s2 ; // Class type to Class type Conversion

But if we have to perform these three operations, we must be write a conversion routine
as describe below.

Basic (Built in) to Class type Conversion

The conversion from basic type to class type can be performed by using only one argument
constructor write in a class and this is called conversion constructor. Let us see the example
of convert basic type to class type.

Example (Demonstrate Basic to Class type conversion using conversion constructor)

#include<iostream.h>
#include<conio.h>
#include<string.h>
class test
{
int len;
char *s;
public:
test()
{
len=0;
s=NULL;
}
test(char *s1) // called conversion constructor which
{ // will convert basic type to class type
len = strlen(s1);
s = new char(len+1);
strcpy(s,s1);
}
void show()
{
cout<<"String is: "<<s<<endl;
}
};

Prepared by | Hemang R. Chath


BCA-III C++ and Object Oriented Programming
main()
{
clrscr();
test str1;
char *name = "Kishan";
str1 = name; // convert name(basic type) to class(str1)
// call conversion function
str1.show();
getch();
return 0;
}

Output:
String is: Kishan

In above program, the statement str1 = name ; is convert a name (character type data)
to str1 a class type (user defined).

Class type to Basic (Built in) type Conversion

The constructor function does not support this type of conversion, for this type of conversion
we must be writing an overloaded casting operator.
An overloaded casting operator convert Class to Basic type conversion, it is also called
conversion function.
The syntax of conversion function is,

operator data-type name ( )


{
Body of Function
}

For example, the overloaded cast operator operator int ( ) convert a class type object to int
type.
The overloaded cast operator operator float ( ) convert a class type object to float type.
The overloaded cast operator operator double ( ) convert a class type object to double type.

Prepared by | Hemang R. Chath


BCA-III C++ and Object Oriented Programming
The overloaded cast operator operator char * ( ) convert a class type object to char type.
The casting operator (Conversion function) should satisfy the following conditions:

1. It must be a class member


2. It must not specify a return type
3. It must not have any arguments

Example (To demonstrate Class to Basic type conversion using conversion function)

#include<iostream.h>
#include<conio.h>
#include<string.h>

class test
{
int len;
char *s;

public:
test()
{
len=0;
s=NULL;
}

test(char *s1)
{
len = strlen(s1);
s = new char(len+1);// provide exact location to string s
strcpy(s,s1);
}
operator char *()
{
return s;
}

void show()
{
cout<<"String is: "<<s<<endl;
}

};

Prepared by | Hemang R. Chath


BCA-III C++ and Object Oriented Programming
main()
{
clrscr();
test str1 = "Rajesh";
char *name;
name = str1; // convert class(str1) to basic (name) type
// call conversion function

str1.show();
cout<<endl<<name;
getch();
return 0;
}

Output:
String is: Rajesh
Rajesh

Class type to Class type Conversion

If a class name test1 have object t1 and class test2 have object t2, then we can write a
statement like,
t1 = t2 ; // two different class objects
The class test2 type data is converted to the class test1 type data and converted value is
assigned to the object t1. In above case we can say that conversion takes place from class
test2 to test1, where test2 is called source class and class test1 is called destination class.
If we have to perform above conversion, we must be write an either conversion constructor
or conversion function.
So there are two methods used for class to class type conversion, which is depending upon
the conversion routine write in either source class or destination class.
If conversion routine writes in a source class, then we use a cast operator that will write in
a source class to perform above operation.
If conversion routine writes in a destination class then we use a conversion constructor that
will write in a destination class to perform above operation.

Prepared by | Hemang R. Chath


BCA-III C++ and Object Oriented Programming
For class to class conversion there are two methods used:

1. Casting Operator write in a Source Class


2. Conversion Constructor write in a Destination Class

Example (Conversion Routine write in a Source Class)

#include<iostream.h>
#include<conio.h>

class test1
{
int x;
public:
test1()
{
x = 0 ;
}

test1(int a)
{
x = a ;
}

void show()
{
cout<<"Value of x is: "<< x ;
}
};
class test2
{
int y;
public:
test2()
{
y = 0 ;
}
test2(int b)
{
y = b ;
}

Prepared by | Hemang R. Chath


BCA-III C++ and Object Oriented Programming
void show()
{
cout<<"Value of y is: "<< y << endl ;
}

operator test1() // Cast Operator for class to class conversion


{
int z = y;
return test1(z) ;
}
};
main()
{
clrscr();
test1 t1;
test2 t2(15);
t2.show();
t1 = t2 ; // Call casting operator
t1.show();
getch();
return 0;
}

Output:
Value of y is: 15
Value of x is: 15

In above program, we write casting operator in a test2 class which is source class, that
will convert a class destination object (t1) to source class object (t2).
So a statement t1 = t2 ; will indicate the conversion of one class object to another.

Prepared by | Hemang R. Chath


BCA-III C++ and Object Oriented Programming
Example (Conversion Routine write in a Destination Class)

#include<iostream.h>
#include<conio.h>
class test2
{
int y;
public:
test2()
{
y = 0 ;
}
test2(int b)
{
y = b ;
}
void show()
{
cout<<"Value of y is: "<< y << endl ;
}
int getdata()
{
return y;
}
};
class test1
{
int x;
public:
test1()
{
x = 0 ;
}
test1(int a)
{
x = a ;
}
void show()
{
cout<<"Value of x is: "<< x ;
}

Prepared by | Hemang R. Chath


BCA-III C++ and Object Oriented Programming
test1(test2 t) //constructor routine in destination class for
//class to class conversion, where t is object of class test2
{

x = t.getdata();
}
};
main()
{
clrscr();
test1 t1;
test2 t2(10);
t2.show();
t1 = t2 ; // call conversion constructor
t1.show();
getch();
return 0;
}

Output:
Value of y is: 10
Value of x is: 10

In above program, we write a conversion constructor in class test1 which is destination


class, in this constructor we call a getdata() member function of a class test2, which is
called by using object t of class test2, which will get a value of y from the class test2.

Prepared by | Hemang R. Chath


BCA-III C++ and Object Oriented Programming

COMPARISON OF DIFFERENT METHOD OF CONVERSION

Below table provide a comparison of different methods of conversion.

Sr. No. Conversion From Methods used for Conversion

1. Basic to Class type Using Conversion Constructor

2. Class to Basic type Using Casting Operator

3. Class to Class type

1 Routine write in Source Class Using Casting Operator

2 Routine write in Destination Using Conversion Constructor


Class

Prepared by | Hemang R. Chath

Anda mungkin juga menyukai