Experiment 6: Constant Reference Parameters


Actually, this one is more of a discussion than an experiment.

The Question:

Suppose I am writing a function, and one of its parameters is a class object that is received, but not passed back (i.e., whose movement is IN). If I declare the parameter as a value parameter, then when the function is called, a copy will be made of the corresponding (class object) argument. Since a class object is typically much larger than a character or number, copying a class object can take a lot of time, which means that passing a class object to a function via a value parameter can be very time-consuming. Is there any way to avoid wasting this time?

The Answer. The key to solving this problem is to combine two seemingly unrelated pieces of information:

  1. A reference parameter is an alias of its argument; and
  2. A const object is a read-only object.
That is, a reference parameter for a class object does not store a copy of the corresponding argument, but stores the address of that object (usually just 32 bits). For example, in lab 4, we wrote a Piglatin() function this way:
   string Piglatin(string englishWord)
   {
      // ...
   }
If englishWord contains any word of more than 4 characters (i.e., jeans), then the value parameter mechanism must make a copy of this word. Copying more than 4 types requires more time than storing a 32-bit address (4 bytes).

If we were to instead write our PigLatin() function as follows:

   string Piglatin(string & englishWord)
   {
      // ... 
   }
Then englishWord will store the 32-bit address of its corresponding argument, and since 32 bits == 4 bytes, this will require less time for any string of more than four characters.

However, this approach opens up a dangerous possibility of our function mistakenly changing the value of englishWord which, since the movement of englishWord is IN, would be a logic error. If it were to make this error, the compiler would be unable to point out our mistake, since we have declared englishWord as a reference parameter.

The solution is to declare englishWord as a const reference parameter:

   string Piglatin(const string & englishWord)
   {
      // ...
   }
By preceding a reference parameter with the keyword const, we tell the compiler to
  1. Pass the address of the argument to this parameter, instead of copying the entire argument; and
  2. To treat this parameter as a read only object -- any attempt to change it should be flagged as an error.
We'll conclude with the rules of thumb for parameter passing. Try to keep them in mind from now on as you write functions involving class (and non-class) objects.


Back to the Lab Exercise

Forward to the Next Experiment


Copyright 1998 by Joel C. Adams. All rights reserved.