Date post: | 06-Apr-2018 |
Category: |
Documents |
Upload: | ecomputernotes |
View: | 234 times |
Download: | 0 times |
of 32
8/3/2019 Computer Notes - Operator Overloading
1/32
Operator overloadingOperator overloading
http://ecomputernotes.com
8/3/2019 Computer Notes - Operator Overloading
2/32
Operator overloadingOperator overloadingConsider the following class:Consider the following class:
class Complex{class Complex{
private:private:
double real,double real, imgimg;;public:public:
ComplexComplexAdd(constAdd(const Complex &);Complex &);
ComplexComplex Subtract(constSubtract(const Complex &);Complex &);ComplexComplexMultiply(constMultiply(const Complex &);Complex &);
}} http://ecomputernotes.com
8/3/2019 Computer Notes - Operator Overloading
3/32
Operator overloadingOperator overloading
Function implementation:Function implementation:
ComplexComplex Complex::AddComplex::Add((
const Complex & c1){const Complex & c1){
Complex t;Complex t;
t.realt.real = real + c1.real;= real + c1.real;
t.imgt.img == imgimg + c1.img;+ c1.img;
return t;return t;
}} http://ecomputernotes.com
8/3/2019 Computer Notes - Operator Overloading
4/32
Operator overloadingOperator overloading
The following statement:The following statement:
Complex c3 = c1.Add(c2);Complex c3 = c1.Add(c2);
Adds the contents ofAdds the contents ofc2c2 toto c1c1 andand
assigns it toassigns it to c3c3 (copy constructor)(copy constructor)
http://ecomputernotes.com
8/3/2019 Computer Notes - Operator Overloading
5/32
Operator overloadingOperator overloading
To perform operations in a singleTo perform operations in a single
mathematical statementmathematical statement e.ge.g::
c1+c2+c3+c4c1+c2+c3+c4
We have to explicitly write:We have to explicitly write:
c1.Add(c2.Add(c3.Add(c4)))c1.Add(c2.Add(c3.Add(c4)))
http://ecomputernotes.com
8/3/2019 Computer Notes - Operator Overloading
6/32
Operator overloadingOperator overloading
Alternative way is:Alternative way is:
t1 = c3.Add(c4);t1 = c3.Add(c4);t2 = c2.Add(t1);t2 = c2.Add(t1);
t3 = c1.Add(t2);t3 = c1.Add(t2);
http://ecomputernotes.com
8/3/2019 Computer Notes - Operator Overloading
7/32
Operator overloadingOperator overloading
If the mathematical expression is big:If the mathematical expression is big:
Converting it to C++ code will involveConverting it to C++ code will involvecomplicated mixture of function callscomplicated mixture of function calls
Less readableLess readable
Chances of human mistakes are very highChances of human mistakes are very high
Code produced is very hard to maintainCode produced is very hard to maintain
http://ecomputernotes.com
8/3/2019 Computer Notes - Operator Overloading
8/32
Operator overloadingOperator overloading
C++ provides a very elegant solution:C++ provides a very elegant solution:
Operator overloadingOperator overloading
C++ allows you to overload commonC++ allows you to overload commonoperators likeoperators like ++,, -- oror ** etcetc
Mathematical statements donMathematical statements don
t have tot have to
be explicitly converted into function callsbe explicitly converted into function calls
http://ecomputernotes.com
8/3/2019 Computer Notes - Operator Overloading
9/32
Operator overloadingOperator overloading
Assume that operatorAssume that operator + has+ has beenbeenoverloadedoverloaded
Actual C++ code becomes:Actual C++ code becomes:c1+c2+c3+c4c1+c2+c3+c4
The resultant code is very easy toThe resultant code is very easy toread, write and maintainread, write and maintain
http://ecomputernotes.com
8/3/2019 Computer Notes - Operator Overloading
10/32
Operator overloadingOperator overloading
C++ automatically overloads operatorsC++ automatically overloads operators
for prefor pre--defined typesdefined typesExample of predefined types:Example of predefined types:
intintfloatfloat
doubledouble
charchar
longlong
http://ecomputernotes.com
8/3/2019 Computer Notes - Operator Overloading
11/32
Operator overloadingOperator overloading
Example:Example:
float x;float x;
intint y;y;
x = 102.02 + 0.09;x = 102.02 + 0.09;
Y = 50 + 47;Y = 50 + 47;
http://ecomputernotes.com
8/3/2019 Computer Notes - Operator Overloading
12/32
Operator overloadingOperator overloading
The compiler probably calls the correctThe compiler probably calls the correct
overloaded low level function for additionoverloaded low level function for addition i.ei.e::
//// for integer addition:for integer addition:
Add(intAdd(int
a,a,
intint
b)b)
//// for float addition:for float addition:
Add(floatAdd(float a, float b)a, float b)
http://ecomputernotes.com
8/3/2019 Computer Notes - Operator Overloading
13/32
Operator overloadingOperator overloading
Operator functions are not usuallyOperator functions are not usuallycalled directlycalled directly
They are automatically invoked toThey are automatically invoked toevaluate the operations they implementevaluate the operations they implement
http://ecomputernotes.com
8/3/2019 Computer Notes - Operator Overloading
14/32
Operator overloadingOperator overloading
List of operators that can beList of operators that can beoverloaded in C++:overloaded in C++:
http://ecomputernotes.com
8/3/2019 Computer Notes - Operator Overloading
15/32
Operator overloadingOperator overloading
List of operators that canList of operators that cant bet beoverloaded:overloaded:
Reason: They take name, rather thanReason: They take name, rather thanvalue in their argument except forvalue in their argument except for ?:?:
?:?: is the only ternary operator in C++is the only ternary operator in C++and canand cant be overloadedt be overloaded
8/3/2019 Computer Notes - Operator Overloading
16/32
Operator overloadingOperator overloading
The precedence of an operator isThe precedence of an operator isNOTNOT affected due to overloadingaffected due to overloading
Example:Example:c1*c2+c3c1*c2+c3
c3+c2*c1c3+c2*c1
both yield the same answerboth yield the same answer
8/3/2019 Computer Notes - Operator Overloading
17/32
Operator overloadingOperator overloading
AssociativityAssociativity isis NOTNOT changed duechanged dueto overloadingto overloading
Following arithmetic expressionFollowing arithmetic expressionalways is evaluated from left to right:always is evaluated from left to right:
c1 + c2 + c3 + c4c1 + c2 + c3 + c4
8/3/2019 Computer Notes - Operator Overloading
18/32
Operator overloadingOperator overloading
Unary operators and assignmentUnary operators and assignmentoperator are right associative,operator are right associative, e.ge.g::
a=b=ca=b=c is same asis same as a=(b=c)a=(b=c)
All other operators are leftAll other operators are leftassociative:associative:
c1+c2+c3c1+c2+c3 is same asis same as(c1+c2)+c3(c1+c2)+c3
http://ecomputernotes.com
8/3/2019 Computer Notes - Operator Overloading
19/32
Operator overloadingOperator overloading
Always write code representing theAlways write code representing theoperatoroperator
Example:Example:Adding subtraction code inside the +Adding subtraction code inside the +operator will create chaosoperator will create chaos
http://ecomputernotes.com
8/3/2019 Computer Notes - Operator Overloading
20/32
Operator overloadingOperator overloading
Creating a new operator is a syntax errorCreating a new operator is a syntax error
(whether unary, binary or ternary)(whether unary, binary or ternary)
You cannot createYou cannot create $$
http://ecomputernotes.com
8/3/2019 Computer Notes - Operator Overloading
21/32
Operator overloadingOperator overloading
ArityArity of an operator is NOT affected byof an operator is NOT affected by
overloadingoverloading
Example:Example:
Division operator will take exactly two operands inDivision operator will take exactly two operands in
any case:any case:
b = c / db = c / d
http://ecomputernotes.com
8/3/2019 Computer Notes - Operator Overloading
22/32
Binary operatorsBinary operators
Binary operators act on two quantitiesBinary operators act on two quantities
Binary operators:Binary operators:
http://ecomputernotes.com
8/3/2019 Computer Notes - Operator Overloading
23/32
Binary operatorsBinary operators
General syntax:General syntax:
Member function:Member function:
TYPETYPE11 CLASS::operatorCLASS::operator B_OP(B_OP(
TYPETYPE22 rhsrhs){){
......
}}
http://ecomputernotes.com
8/3/2019 Computer Notes - Operator Overloading
24/32
Binary operatorsBinary operators
General syntax:General syntax:
NonNon--member function:member function:
TYPETYPE11 operator B_OP(TYPEoperator B_OP(TYPE22 lhs,lhs,TYPETYPE33 rhsrhs){){
......
}}
http://ecomputernotes.com
8/3/2019 Computer Notes - Operator Overloading
25/32
Binary operatorsBinary operators
TheTheoperator OPoperator OPmust have at leastmust have at least
one formal parameter of type class (userone formal parameter of type class (user
defined type)defined type)
Following is an error:Following is an error:
intint operator + (operator + (intint,, intint););
http://ecomputernotes.com
8/3/2019 Computer Notes - Operator Overloading
26/32
Binary operatorsBinary operators
Overloading + operator:Overloading + operator:
class Complex{class Complex{
private:private:
double real,double real, imgimg;;public:public:
Complex operator +(constComplex operator +(constComplex &Complex & rhsrhs););
};};http://ecomputernotes.com
8/3/2019 Computer Notes - Operator Overloading
27/32
Binary operatorsBinary operators
ComplexComplex Complex::operatorComplex::operator +(+(const Complex &const Complex & rhsrhs){){
Complex t;Complex t;
t.realt.real = real += real + rhs.realrhs.real;;t.imgt.img == imgimg ++ rhs.imgrhs.img;;
return t;return t;
}}
http://ecomputernotes.com
8/3/2019 Computer Notes - Operator Overloading
28/32
Binary operatorsBinary operators
The return type is Complex so as toThe return type is Complex so as to
facilitate complex statements like:facilitate complex statements like:Complex t = c1 + c2 + c3;Complex t = c1 + c2 + c3;
The above statement is automaticallyThe above statement is automaticallyconverted by the compiler intoconverted by the compiler intoappropriate function calls:appropriate function calls:
((c1.operator +(c2)c1.operator +(c2))).operator.operator+(c3);+(c3);
http://ecomputernotes.com
8/3/2019 Computer Notes - Operator Overloading
29/32
Binary operatorsBinary operators
If the return type wasIf the return type wasvoidvoid,,class Complex{class Complex{
......
public:public:
void operator+(void operator+(
const Complex &const Complex & rhsrhs););
};};
http://ecomputernotes.com
8/3/2019 Computer Notes - Operator Overloading
30/32
Binary operatorsBinary operators
voidvoidComplex::operator+(constComplex::operator+(constComplex &Complex & rhsrhs){){
real =real = realreal ++ rhs.realrhs.real;;
imgimg == imgimg ++ rhs.imgrhs.img;;
};};
http://ecomputernotes.com
8/3/2019 Computer Notes - Operator Overloading
31/32
Binary operatorsBinary operators
we have to do the same operationwe have to do the same operationc1+c2+c3c1+c2+c3 as:as:
c1+c2c1+c2c1+c3c1+c3
// final result is stored in c1// final result is stored in c1
http://ecomputernotes.com
8/3/2019 Computer Notes - Operator Overloading
32/32
Binary operatorsBinary operators
Drawback of void return type:Drawback of void return type:
Assignments and cascaded expressions areAssignments and cascaded expressions arenot possiblenot possible
Code is less readableCode is less readable
Debugging is toughDebugging is tough
Code is very hard to maintainCode is very hard to maintain
http://ecomputernotes.com