1 aharta eec
New state of object w1
After the execution of the operator function, the state of object w1
is as shown in the Figure 13.12 Figure 13.12: Object wi
13.6 Overload
Recall from Chapter 3, >, > =, =, and |= are called as relational operators in C++.
se operators check if a specific relationship is true between two of its operands and
) Boolean values as a result of this check. The relational operator returns 1 if the
clationship between the operands is true, and returns zero if the relation false. For
example, i! « and b ate integer variables and we apply a check a>=b, then the
result as 1 if value of variable a is greater than or equal tob, and
value of a is less than b.-As relational operators always return B
are generally used as a conditional expression inside a deci
‘of C++. In this example, we will learn overloading of relati
capabilities to work with objects. .
Lotus use class Weight from)
> and <=. This means that we
operator<=(), inside class WThe expression
will invoke operators () funetion using object w1 by passing w2 as an argument. This
is because wi appears on the left hand side of the operator and w2 on the right hand side.
\We know that the result of comparison always has to be a Boolean value (i.c.,0 or 1). Hence
the retum type of each of the operator functions is set as int. If the relation between the two
objects is true, the operator function returns], and it returns 0 otherwise. Since Weight is
our own class, we can define our own rules on how to compare its objects. Here, each Weight
object is specified in terms of kilograms and grams; hence, to compare two Weight objects
2 and w2, we must first get them into a single unit. The operator function converts both the
ts fully into grams and then compares the converted values with each other. Let g1 and
2 be tully converted gram values of weights w1 and w2 then g1 and g2 « be calculated as
a “
wl. kilogram*1000+w1.gram;
ilogram*1000+w2.1
then it implies that
the comparison. The main() ft
and w2 as slming with C++
jer Programming
‘o.com
State of object wa
; captured from
py
ssain() faction
r
Old state of|
object wi
ttgieg2)
|e tetiae ae ee
coe
. function, In this case the
{function returns 2 indicating
cama
1 wight w2
kilogram=20
gram=300
Object wa is passed
san argument
and is intialized to the
formal argument
Dic nesta
sit vee ates
tarot vn
fVe operators (Weight t)
kilogram*1000+gram;
=t.kKilogram*1000+t.gram;
if (gl>g2)
{
return 1;
}
else
return 0;
}
}
int operator<=(Weight t)
{
long gi =kilogram*1000+gram;
long g2 =t-kilogram*1000+t.gram;
Operator Overloading
+
ng720
We
+
ght
ght
yht
Computer Programming with C44
w2 (20,300);
w3 (110,100)
wa (25,450);
"Condition w1lsw2
is TRUE" <
class Integer
public
Integer ()
{
}
Integer (int p)
‘ t
a=p; .
}
Integer operator++()
{
Integer res;
res.a = +ta;cout<<"Object 04"<