Skip to main content

How To Think Like a Computer Scientist C++ Edition The Pretext Interactive Version

Section 11.6 A more complicated example

Although the process of transforming functions into member functions is mechanical, there are some oddities. For example, after operates on two Time structures, not just one, and we can’t make both of them implicit. Instead, we have to invoke the function on one of them and pass the other as an argument.
Inside the function, we can refer to one of the them implicitly, but to access the instance variables of the other we continue to use dot notation.
bool Time::after(const Time& time2) const {
  if (hour > time2.hour) return true;
  if (hour < time2.hour) return false;

  if (minute > time2.minute) return true;
  if (minute < time2.minute) return false;

  if (second > time2.second) return true;
  return false;
}
To invoke this function:
if (doneTime.after(currentTime)) {
  cout << "The bread will be done after it starts." << endl;
}
You can almost read the invocation like English: “If the done-time is after the current-time, then…”
Listing 11.6.1. This active code is another practical example using the after function. Feel free to modify the time that school gets out, and the time that the track meet starts, if you wish!

Checkpoint 11.6.1.

Which is/are true about the Time::after member function?
  • There is only one Time parameter.
  • Incorrect! There are actually two Time parameters, one of them is implicit.
  • The function operates on two Time objects.
  • Correct! There are two Time objects - the implicit one and time2.
  • The function is invoked on time2.
  • Incorrect! The function is invoked on the implicit Time object.
  • "hour" and "minute" refer to the hour and minute of the implicit Time object.
  • Correct!

Checkpoint 11.6.2.

In a function that operates on four structures, how many of them are accessed with dot notation?
  • One
  • Incorrect! There is One implicit structure.
  • Two
  • Incorrect! Keep in mind there are 4 structures and 1 is implicit.
  • Three
  • Correct! There is One implicit structure, and three structures that need to be accessed with dot notation.
  • Four
  • Incorrect! We shouldn’t need to use dot notation for all of them!

Checkpoint 11.6.3.

Create the Dog::is_older() function. This function checks if the current Dog is older than another Dog. The function is invoked on the current Dog.
You have attempted 1 of 4 activities on this page.