Homework 3

DUE: Sunday 4/17, 11 pm (no late turn-in)


Collaboration policy: Collaboration is strongly ENCOURAGED, although of course, you should still submit your own solutions. Questions on exams and quizzes are frequently taken directly from homeworks.

Turn-in: Compose your homework on a simple text editor such as emacs or Notebook, and save it as a text file ("text-only format") with the extension .txt or .cpp
Submit your work electronically to the hw3 folder on the cs secure server.
Remember to include the header template.


The following exercises extend the material covered in lab last week

Start with the following skeleton class Rational:
class Rational
{
   public:
      Rational();
      Rational(int num, int den);
      void display_fract() const;
      int get_num() const;
      int get_den() const;
   private:
      int numerator;
      int denominator;
};
In all cases, you must give an example of how the function is to be used in an application.
e.g.
   Rational test_fraction(7, 13);       //declares & initializes a Rational called test_fraction to 7/13
   display(test_fraction);              //outputs 7/13 to the console
  1. Write definitions for the five functions declared in the class

  2. Write a non-member function that will add two rational numbers
    The function declaration is:
    Rational sum_fracts(Rational lhs_fract, Rational rhs_fract);
  3. Write a member function to perform the same task.
    The declaration (inside the class definition) is:
    Rational add_fract(Rational rhs_fract);
    Remember that the sum of two fractions n1/d1 and n2/d2 is given by (n1*d2 + n2*d1) / d1*d2
    Note: review the notions of implicit and explicit parameters in member functions, and section 6.8.

  4. Now study the "Advanced Section" relating to operator overloading (advanced topic 6.2, p. 227).
    Re-write the member function in question 3 using the overloaded operator +
    The function declaration (inside the class definition) is:
            Rational operator +(Rational rhs_fract);
    The function definition header is:
            Rational::Rational operator +(Rational rhs_fract)
            {
                // function definition
            }
    Note that, since this is a member function, we only supply one explicit parameter, the right-hand-side; the implicit parameter provides the left-hand-side fraction. The function will be invoked in an application as follows:
            Rational f1, f2;
            Rational sum;
               //some code that sets the values of f1 and f2
            sum = f1 + f2;
              //f1 is the implicit parameter, f2 is the explicit parameter.