11.9. One last example

The final example we’ll look at is addTime:

Time addTime2 (const Time& t1, const Time& t2) {
  double seconds = convertToSeconds (t1) + convertToSeconds (t2);
  return makeTime (seconds);
}

We have to make several changes to this function, including:

  1. Change the name from addTime to Time::add.

  2. Replace the first parameter with an implicit parameter, which should be declared const.

  3. Replace the use of makeTime with a constructor invocation.

Here’s the result:

Time Time::add (const Time& t2) const {
  double seconds = convertToSeconds () + t2.convertToSeconds ();
  Time time (seconds);
  return time;
}

The first time we invoke convertToSeconds, there is no apparent object! Inside a member function, the compiler assumes that we want to invoke the function on the current object. Thus, the first invocation acts on this; the second invocation acts on t2.

The next line of the function invokes the constructor that takes a single double as a parameter; the last line returns the resulting object.

Feel free to try out the add function in the active code below!

Before you keep reading...

Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.

You have attempted 1 of 4 activities on this page