CS 102 Lecture Notes

Week Six, Monday/Tuesday: Operator Overloading

Example Report

I have created an example report for my applet version of the lunar lander project. This report provides an example of technical writing that students might find interesting. This is not to say that all student reports must look like this one, but that there are some report features that you may find useful in the future.

Operator Overloading

Operator overloading provides programming convenience. Overloading the assignment operator (=) is required for classes that use dynamic memory (a copy constructor is also rquired).

See DD figure 8.1 (page 466) for a list of operators that can be overloaded. We will go over some of the more frequently overloaded operators.

Overloading Stream-Insertion and Stream-Extraction Operators

This form of operator overloading is handy not only for printing information to the screen, but for file I/O. The functions are declared as friends to the class because the operators must have left operands of types ostream and istream. Normally, the use of friend classes should be minimized because they violate encapsulation. See the example in DD page 469.


The following is some review material from the introductory course that we will go over in class if time allows:

Pointer Operators

Star and Ampersand (* and &) are the dereferencing (AKA indirection) and address-of operators, respectively.
  int y = 5;
  int *yPtr;

  yPtr = &y;

  cout << *yPtr << endl;

  *yPtr = 9;

Calling Functions by Reference

Passing a variable (or object) by pointer allows the called function to operate on that variable (or object). This is not to be confused by "reference parameters" which do much the same thing.

Pointer Arithmetic

One can advance through an array by incrementing the array pointer. Avoid this unless you have a really good reason for doing it. Maintainability and portability problems can arise.

Arrays of Pointers

For example a C-string array:
  char *suit[4] = {"Hearts", "Diamonds", "Clubs", "Spades"};

Function Pointers

A pointer to a function may be passed as a parameter to another function. This allows function behavior to be modified on the fly to make your code even harder to understand and maintain. Use this technique sparingly (only when you have a good reason to).

Character and String Fundamentals

String library: copy, catenation, comparison.


This page established September 26, 1999; last updated February 13, 2000.