Object Oriented Programming (OOP) - CS304 Power Point Slides Lecture 16
Object Oriented Programming (OOP) - CS304 Power Point Slides Lecture 16
16
Operator overloading
Consider
Operator overloading
Function
implementation:
Complex Complex::Add(
const Complex & c1){
Complex t;
t.real = real + c1.real; t.img } = img + c1.img; return t;
Operator overloading
The
following statement:
Complex c3 = c1.Add(c2);
Operator overloading
To
c1.Add(c2.Add(c3.Add(c4)))
Operator overloading
Alternative
way is:
Operator overloading
If
big:
Less readable
Chances of human mistakes are very high
Operator overloading
C++
Operator overloading
Assume Actual
Operator overloading
C++
of predefined types:
int
float double char long
Operator overloading
Example:
Operator overloading
The compiler probably calls the correct overloaded low level function for addition i.e:
// for integer addition:
Add(int a, int b)
// for float addition: Add(float a, float b)
Operator overloading
Operator
They
Operator overloading
List
Operator overloading
List
They take name, rather than value in their argument except for ?: ?: is the only ternary operator in C++ and cant be overloaded
Operator overloading
The
c1*c2+c3
c3+c2*c1
both yield the same answer
Operator overloading
Associativity
Following
Operator overloading
Unary
Operator overloading
Always
Operator overloading
Creating
Operator overloading
Arity
Binary operators
Binary Binary
Binary operators
General
syntax:
Member function:
TYPE1 CLASS::operator B_OP( TYPE2 rhs){ ... }
Binary operators
General
syntax:
Non-member function:
TYPE1 operator B_OP(TYPE2 lhs, TYPE3 rhs){ ... }
Binary operators
The
operator OP must have at least one formal parameter of type class (user defined type)
Following
is an error:
Binary operators
Overloading
+ operator:
Binary operators
Complex Complex::operator +( const Complex & rhs){ Complex t; t.real = real + rhs.real; t.img = img + rhs.img;
return t;
}
Binary operators
The
above statement is automatically converted by the compiler into appropriate function calls:
(c1.operator +(c2)).operator +(c3);
Binary operators
If
Binary operators
void Complex::operator+(const Complex & rhs){
Binary operators
we
c1+c3
Binary operators
Drawback
Debugging is tough
Code is very hard to maintain