« Operator overloading in C++
Operators like + , - or * are not defined for our custom classes
This is because +
, -
or *
operators are not defined for our custom classes we need to define them for our classes to use them .When we define these operators for our classes, it is called operator overloading.
overloading + - * operators also known as binary operators
1Fraction operator+(Fraction const &f2) const2{3 int lcm = this->denominator * f2.denominator;4 int x = lcm / this->denominator;5 int y = lcm / f2.denominator;6 int num = x * this->numerator + y * f2.numerator;7 Fraction f3(num, lcm);89 // this->numerator=num;10 // this->denominator=lcm;11 f3.simplify();12 return f3;13}1415Fraction operator*(Fraction const &f2) const16{17 int num = this->numerator * f2.numerator;18 int den = this->denominator * f2.denominator;19 Fraction f3(num, den);20 f3.simplify();21 return f3;22}2324bool operator==(Fraction const &f2) const25{26 return (this->numerator == f2.numerator && this->denominator == f2.denominator);27}
overloading ++ pre-increment and post-increment operators also known as unary operators
Whenever a function returns a value it is first stored in a buffer memory then assigns to wherever it needs to be assigned
For full class code to try out the code yourself: