The Rational Class .cpp file, a better version

The .cpp file   --   the whole thing: rat2.cpp

The constructor is identical to what was seen in the simple Rational class. All the code of the arithmetic operators, e.g.,   operator+,   is also identical (operator+ to the add function, and so on) .

What is the this pointer?
The   operator<   and   operator>   are straightforward, returning a bool value. But look at the   operator<= function:
bool Rational::operator<=(const Rational& r) const {
   return *this == r || *this < r;
}
Since   operator<   and   operator==   are already written, instead of rewriting that code, we simply call those functions using   ||   (OR) so if either is true, then   operator<=   will be true. To call the other functions, we need to have our hands on the current object, or this object. We can do this through the this pointer since every object contains the this pointer, a pointer to itself.

Because this is a pointer and not a reference, it must be dereferenced. We dereference using an asterisk, the   * , in front of it. So, the code
   *this 
is the actual object. It's just as though we were in main and we had the object   x . Remember that   *this == r   is the same as   (*this).operator==(r) . The parentheses are needed around *this because of the precedence of operators. A more common way to write it when using pointers is   this->operator==(r) . (Pointers are discussed in more detail in the pointer section.)

Notice how easily   operator+=   can be written using   operator+:
Rational& Rational::operator+=(const Rational& a) {
   *this = *this + a;
   reduce();
   return *this;
}
Notice the return. A Rational& , the address of   *this , is returned.

Defining operator<< and operator>>
Even though this is a global function (not belonging to any class) because it is for a Rational object, it is typically put in the same file with the member functions. But remember that it is not a member function:
ostream& operator<<(ostream &output, const Rational &r) {
   if (r.denominator == 0)
      ...
				       
   return output;
}
Notice that there is no binary scope operator connecting it to the Rational class since it's not a member function. Also, don't forget that you must qualify the members when you use them. For example, when you use the data member denominator, it must be referred to as r.denominator, the parameter object.

The function   operator>>   is similar in nature.