1. Binary operator #
Created Saturday 11 January 2020
Rationale:
f1+f2
, mathematically can be written asf1.add(f2)
- This can be improvised to
f1+f2
in code. - Instead of
Fraction add(const Fraction & t)
, writeFraction operator+(const Fraction &t)
.
Body is the same for both.
- Think this like,
object1.
is replaced byoperator+
and+
is basically the function name.
Notes:
- No space should be present between operator and symbol.
- The whole expression is replaced by the return type.
- We can make the operator function as a const, if it does not change anything from the object.
In C++ we can overload most operators like +
, -
, []
, ->
etc. But we cannot overload all the operators. Some of the operators cannot be overloaded, viz:
.
Dot operator? :
Ternary operator::
Scope resolution operator.*
Pointer to member operatorsizeof
object size operatortypeid
object type operator
DTSPST These operators cannot be overloaded because if we overload them it will make serious programming issues.
For an example the sizeof operator returns the size of the object or datatype as an operand. This is evaluated by the compiler. It cannot be evaluated during runtime. So we cannot overload it.
Some examples:
Fraction operator+(Fraction const &f2)
{
Fraction ret(*this);
int lcm = denominator * f2.denominator;
int x = lcm / denominator;
int y = lcm / f2.denominator;
ret.numerator = x * numerator + (y * f2.numerator);
ret.denominator = lcm;
ret.simplify();
return ret;
}
// Replace + by ==, -, *,/ . All these are binary functions.