The Rational Class sample driver (main), a better version

This sample driver shows how the Rational class is used.

The sample driver file   --   the whole thing: rat2driver.cpp

As with the previous version, the rat2.h file must be included here as well as in the .cpp file. Recall that any identifiers used here, the compiler must know their definitions.

In main, object instantiations are the same:
   Rational w(4), x(7,3), y(3,9), z, copy(x);
Using the default value of one in the constructor, the object   w   will hold the fraction 4/1 in memory. The object   x   will hold 7/3. The object   y   will hold 1/3 after the constructor reduces it to lowest terms. The object   z   will hold 0/1, using both default values in the constructor.

The object   copy   is an exact copy of the object   x  . It uses something called the copy constructor, which always takes an object of the class as its parameter and does a member-wise copy of all the data into the new object being instantiated.

While the code to add looks familiar, x + y, it is actually a function call. The   x + y   is identical to   x.operator+(y). After   x + y   is performed, the assignment is done. Technically, the whole line is   z.operator=(x.operator+(y)). There is also a default   operator=, which also does a member-wise copy of the right operand.
   z = x + y;
   cout << x << " + " << y << " = " << z << endl;
The other arithmetic operators are similar, as are the boolean operators. Inside the cout, the code below is   x.operator>(y):
   cout << x << " is:" << endl;
   cout << ((x > y) ? "    > " : "    not > ");
   cout << y << " according to the overloaded > operator\n";
Test yourself ... what about   x + 5 ... is that legal?
Or, how about   5 + x?

Doing   x + 5   is legal. The compiler views this as   x.operator+(5)   and looks to see if a constructor can construct a Rational object out of 5. Since there is a constructor that can do this, that takes an int parameter, it is called and the integer 5 is cast into the Rational constant 5/1.

On the other hand,   5 + x   gives a compiler error. There is no code for an int to say how to add a Rational to it. To allow   5 + x  , add an operator int() function to the Rational class:
   In class definition: 
      operator int() const;

      Rational::operator int() {
         return numerator/denominator;
Note that this truncates the value (casts to an int using int division since numerator and denominator are both ints) and crashes if the denominator is zero.

We also get an error for the code   z -= x;    
While we've written the   operator-   and the default   operator=   could be used, we haven't defined the function   operator-=, so a compiler error is generated.