Notes and Code (Day 9)

  1. Operator Overloading
Instructor: David Goldschmidt, Ph.D.
Office Hours: after class
Email: click here to email me

Example 18: Operator Overloading

Operators As Non-Member Functions:

  • When it comes to sorting objects using the sort() function, we can define a function that creates a < operator for whatever type of objects we'd like to sort (e.g. Student, Date).
  • Let’s start with syntax. The following expressions are actually treated as function calls, as shown in the comments:
  • if ( a < b )   // if ( operator< ( a, b ) )
    {
      // ...
    
      z = x + y;   // z = operator+ ( x, y );
    
  • When we want to write our own operators, we write them as functions using the operator keyword. For example, if we define operator< for Student objects as follows:
  • bool operator< ( const Student& stu1, const Student& stu2 )
    {
      return stu1.last_name() < stu2.last_name() ||
             ( stu1.last_name() == stu2.last_name() && stu1.first_name() < stu2.first_name() );
    }
    
  • Then the following statement will sort Student objects into alphabetical order by last name, then first name:
  • sort( students.begin(), students.end() );
    

Exercises:

  • Write an operator< function for comparing two Date objects.
  • Write an operator== function for comparing two Date objects.
  • Write an operator+ function for adding a given number of days (i.e. an int) to a Date object.