Object-Oriented Programming
(OOP)
Binary operators
The return type is Complex so as to
facilitate complex statements like:
◦ Complex t = c1 + c2 + c3;
Theabove statement is automatically
converted by the compiler into
appropriate function calls:
◦ (c1.operator +(c2)).operator
+(c3);
Binary operators
The binary operator is always called with
reference to the left hand argument
Example:
oIn c1+c2, c1.operator+(c2)
oIn c2+c1, c2.operator+(c1)
Binary operators
The above examples don’t handle the
following situation:
◦ Complex c1;
◦ c1 + 2.325
Todo this, we have to modify the
Complex class
Binary operators
►Modifying the complex class:
class Complex{
...
Complex operator+(const
Complex & rhs);
Complex operator+(const
double& rhs);
};
Binary operators
Complex operator + (const double&
rhs)
{
Complex t;
t.real = real + rhs;
t.img = img;
return t;
}
Binary operators
►Now suppose:
◦ Complex c2, c3;
►We can do the following:
◦ Complex c1 = c2 + c3;
and
◦ Complex c4 = c2 + 235.01;
Binary operators
►But problem arises if we do the following:
◦ Complex c5 = 450.120 + c1;
►The + operator is called with reference to
450.120
►No predefined overloaded + operator is there
that takes Complex as an argument
Binary operators
►Now if we write the following two functions to
the class, we can add a Complex to a real or
vice versa:
Class Complex{
…
friend Complex operator + (const
Complex & lhs, const double & rhs);
friend Complex operator + (const
double & lhs, const Complex & rhs);
}
Binary operators
Complex operator +(const
Complex & lhs, const
double& rhs)
{
Complex t;
t.real = lhs.real + rhs;
t.img = lhs.img;
return t;
}
Binary operators
Complex operator + (const
double & lhs, const
Complex & rhs)
{
Complex t;
t.real = lhs + rhs.real;
t.img = rhs.img;
return t;
}
Binary operators
Class Complex{
…
Complex operator + (const
Complex &);
friend Complex operator + (const
Complex &, const double &);
friend Complex operator + (const
double &, const Complex &);
};
Binary operators
Other binary operators are overloaded very
similar to the + operator as demonstrated in
the above examples
Example:
◦ Complex operator * (const Complex &
c1, const Complex & c2);
◦ Complex operator / (const Complex &
c1, const Complex & c2);
◦ Complex operator - (const Complex &
c1, const Complex & c2);
Other Binary operators
Overloading += operator:
class Complex{
double real, img;
public:
Complex & operator+=(const Complex &
rhs);
Complex & operator+=(count double &
rhs);
...
};
Other Binary operators
Complex & Complex::operator +=
(const Complex & rhs)
{
real = real + rhs.real;
img = img + rhs.img;
return * this;
}
Other Binary operators
Complex & Complex::operator +=
(const double & rhs)
{
real = real + rhs;
return * this;
}
Other Binary operators
int main(){
Complex c1, c2, c3;
c1 += c2;
c3 += 0.087;
return 0;
}