You are on page 1of 10

13.2.

Defining operator overloading:


Operator overloading is a very ~impl,e process. We need to create an
operator function which will give additional meaning to an operator. To
I • • ►• ~ I '-,

overload an operator, you creat~ an "operatoc function. ~ost often an


operator function l.S a member or a friend of the class for whi~h it i"s defined.
However, there is a slight difference between a me.m ber operator functt'bn
and a friend ·operator function.
The general form of a member operator function is shown here:
return-type class-name: :,operator# (arg-listJ
{
/ / operation to be performed
}
The return type of an operator function is often the class for which it is
defined (however, operator function is free to return _any type). The operator
being overloaded is s:ubstituted for #. For. example, if the operator -+ 1-s b~ing 1
overloaded, the oper~tor function name would pe operator+. The conterits of
arg-list vary depending upon how the operator function is implemented and
the type of operator being overloaded.
Most C++ operators can be overloaded .. The following operators cannot
be overload:
We can overload all the C++ operators except t4e following,
~ ass ,member ac~ess operators ( • ) cl~t op~rator •
2 ~ Cl~ss mempera acce_s s op~rators (. *) - ,.
~ S~~pe resolution operat(l;r ' ; :)
~ Size operator (sizeOof)
~ Conditional operator(?:)

As we know there are three types of operators in C++


(a) Unary Ope~~tor
()p Cf(_( (VI \. ✓ V'- 1 , . -., - , ~ ..,• • l - ~

13.3
----- I

(b) Bina ry Ope rato r


(c) Tern ary Ope rato r
c++ doe sn't allo w ove rloa ding of tern ary ope rato
r. Now we hav e una ry
a.nd bina ry ope rato rs to over load . Let us star t with una
ry ope rato r.

13. 3. Ov erl oad ing una ry ope rat ors :


In c++ we hav e follo wing 1una ry op erat ors una ry ~lus (-),
++ ,_-_- ang j_et c.
As we kno w ~ ~~ gp erat:01:&-wo.1:k only on sing le ope
rand . Wh en a n:e~ ~:E _
operator func tio~-- o~et}~~ d~ a bin ~ _op erat qr, _,the _fuh
ctio_n ~i~! hay e only
; 11 e par ~_e ter'. . 1hi s para met er will rece ive the obje<?t
1 that is on the righ t
side of the ope rato r. In orde r to und erst and how
to ove rloa d a una ry
operator let us con side r a prog ram to over load incr eme
nt ope rato r ++.
/ / Prog ram me to dem ons trat e over load ing of una ry ope
rato r - (una ry
/ /min us) ·
# incl ude <ios trea m.h >
#inc lude <con io.h >
class una ry

int x, y, z;
\ . .
·public:
void getd ata (int a, int , int c);
voicf disp lay (void);
void .ope rato r ;',. ().; / / ove rloa d unru y min us.
};
void una ry :: getd ata (int a, int b, int c)
{
X = a;
y= b;
z = c·
} '
Void una ry : : disp lay (void)
{
cout << x << 11
'' << y << 11
"<< z << end l;

V .
01
d una ry ::ope rato r -()
' {
y = --y ~

Z C - z;
}
main ()
{
'
unary u;
clrscr(); .
u.getdata(-10, -20, 30);
11
cout <<
11
u:
u. display ( ) ;
-u;
cout << "u :" ;
u . display ( ) ;
getcl)-() ;
} - I

Output:
u : -10 -20 30
u : 10 ~20 -30
Explanation: In this program we have define a special member function
to overload unary (-)
void operator - ();
Here operator is a ke)'\\,"Ord to give special meaning to function.The
fu nction operator - ( ) takes no argument because this function is a member
fu nction of the same class, it can directly access the member of the object
which activated it. In main function we have created object of unary class.
The statement
-u;
in ,.,roked operator function. The statement -u; is interpreted as u.operator ...
O; so when compiler encounter this statement then it automatically
in voked operator function.
13.4. Overloading Binary Operators:
Binary operator operates on two operands. When we overload binary
operated we have to pass one argument . Some of the binary operators that
can be overload are
Binary operators arithmetic operators: +, - , *, %
Relational Operator: > , <, >=, <= ,= =, !=
and assignment operator= ,+=,/=,%=
The syntax of Binary operators:
return-type operator#(argume ntl) -
f
l
/ / operation to be performed
}
This is the general syntax for binary operators. It is clear from the syntax
that \Ve have to pass one argument to the function.
13.4.1. Overloading Arithmetic Operators:
The arithmetic operators are + ,-% and / .Let us consider + operator to
add two complex numbers. For this we have to overload + ·operator.
Following is the example to demonstrate this concept.
/ / Program to demonstrate overloading of arithmetic operator
# include<iostream .h>
#include<conio.h >
class complex
- - - = - - - - - - - - - - - - - - - - - - - - - - - - - -- - - - - -

j
-
I
13 .9
l •
f fl oa t x, Y,
pu bl ic :
co m pl ex ()
{
}
t irnag)
complex (f lo at re al , fl oa
{
x = real;
y = im ag ;
}
pl ex c)
complex op er at or +( co m
{ co m pl ex te m p;
te m p.x = x + c. x;
te m p .y = y + c. y;
re tu rn (t em p) ;
}
void di sp la y (void)
{
cout << x << "+ i "< < y
<< "\n ";
}
};
void m ai n ()
{
clrscr();
complex cl (2 .5 , 1. 5) ;
complex c2 (1 .5 , 1. 5) ;
complex c3 ;
cout << "c I = " ;
c1. di sp la y( ) ;
cout << "c2 = ";
c2. di sp la y( ) ;
c3::::cl +c2;
coutc:::c::: "c3 = ";
c3.display( ) ;
getch();
Output:
c l = 2 .5 + j 1.5
c2 = 1.5 + J 1.5.
c3 = 3. 0 + j 6. 2
Explanation: In the above program, the function operator +, is expected
to add two complex values and return a complex value as a result but
receives only one value as argument. The function is ·executed by the
statement
c3 = cl + c2
Here, the object c 1 is used to invoke the function and c2 plays the role of
an argument that is passed to the function. The above statement is
equivalent to
c3 = cl.operator +(c2)
Here, in the operator +() function, the data members of cl are accessed
directly and the data member of c2 are accessed using the dot operator.
Thus in overloading binary operators, the left-hand operand is used to
invoke the operator function and the right-hand operand is passed as an
argument.
Relational Operators:
In c++ we have number of relational operators like >. <. >=<=. = = etc. As
relational operators are binary operator so the process of operator
overloading is same as that of arithmetic operator overloaping. Let us
consider an example to overload = = comparison operator for complex
number class.
I I program to overload = = operator for complex numbers
# include<iostream.h>
#include<conio.h>
class complex
{
float x, y; ·
public:
complex ()
{
}
complex (fl~at real, float imag)
{
x = real·
l •

111 t operator == (complex c)

int result;
if ( X == C.X && y===c .y )
result= 1;
else
result=O;
return (result);
}
void display (void)
{
cout << x << "+ i H<< y << "\n ";
I }
IlJl·
main ()
I
{
complex cl,c2,c3;
, cl = complex (2.5, 1.5);
c2 = complex (1.5, 1.S);
if(c 1== c2)
cout<< "Complex numbers are equal \n";
else
cout< <"\nComplex numbers are not equal \n";
getch();
.. .4 .2 - Str ing Ma nip ula tio n Ua lng Op era tor Ov
11 erlo ading
\\ t han :~ s trin g ma n.ip u1a ting fun ct ion s in
c+ + . To <:o mp ~rc t \VO stri ngs
,, t
h~1, T s1r cn1 p() fun cti ons and s ttc p·y{) is u sed to cop
.,,, v the one ~ r..w g to
Uil- 'th t~r stri ~g. Th ere is one mo re w ay .., ----
to per for m suc h ope rat ion s and it ;s
~h n'u ~ht ope rat or ove rlo adi ng .. It
me ans that "~-e can use ari thm eti c
~p ftt1 tors (>.<. =<= ,= =) for com
par iso n bet we en two stri ng. F or ins tan c
"an u sC' = = ope rat or to com par e e we
two str ing s . For thi s w·e have- to o-ve rlo
:hrs c ope rat ors . ad
Tn u nde r sta nd thi s con cep t let us con
sid er an e ~~m ple to ove rlo ad = =
f0 r com par ing two str ing s.
pro gr am to ove rlo ad = = ope rat or for str
ing s
:1 mcl u de< ios tre am .h>
;1 1ncl ude <co nio .h>
#tn d u d e <st rin g.h >
ci ass str ing

priv a te:
cha r s t r{3 0] ;
pub lic :
stri ng()

strc py( str /' ");

String(ch a r sti ll l)
. ..., __ --- - - ----- --. :-· --
J J I •

stic-py (stt ,strl) ;


l
I

void sho v1 (J
{
cout< <str;
I }

void read(}
{
cou t << En ter string \ n ";
0

cin>> str ~

in t opera tor ==(str ing st robj)


{
if(strc mp (str,st robj.s tr) ==O)
return (1);
else
retum (O);

};
void main()
{
clrscr( );
string s 1, s2;
cout << "Ente r any string l \ n ";
s I .read() ;
cou t<< '' Enter any string 2 \n
11
;

s2 .read() ;
, if(s l ,= =s2)
cout< < ''Strin gs are equal \n";
else
, cout< < ''Strin gs are not equal \ n ";
getch ();
}
l l'. -

.4,. 3. Overlo ading arithm etic assign ment operat ors:


13
·rhe arithm etic assign ment operato rs (+=, -=,*=,/= ,%=) are can be
overload ed in the similar way as that of arithm etic operato rs so that they
can n,ork
v,
with user defined data type.
Let us consid er an examp le to overloa d += and - =opera tors.
/ / Progra m to dmons trate =+ assign ment and - = operato r
# include <iostre am.h>
# include <conio .h>
# include <string .h>
class abc

{
int value;
public:
void input()
{ cout<< " \nEnte r value \n";
cin>>v alue;
}

void display ()
{
cout << "\n value= '' << value;
}

void operato r -=(int x)


f
l

value=v alue-1 ·
} '
};

You might also like