11.4. Another example

Let’s convert increment to a member function. Again, we are going to transform one of the parameters into the implicit parameter called this. Then we can go through the function and make all the variable accesses implicit.

void Time::increment (double secs) {
  second += secs;

  while (second >= 60.0) {
    second -= 60.0;
    minute += 1;
  while (minute >= 60) {
    minute -= 60.0;
    hour += 1;

By the way, remember that this is not the most efficient implementation of this function. If you didn’t do it back in Chapter [time], you should write a more efficient version now.

To declare the function, we can just copy the first line into the structure definition:

struct Time {
  int hour, minute;
  double second;

  print ();
  increment (double secs);

And again, to call it, we have to invoke it on a Time object:

Time currentTime = { 9, 14, 30.0 };
currentTime.increment (500.0);
currentTime.print ();

The output of this program is 9:22:50.

Feel free to change the input and experiment around with the active code below!

Create the Cat object with member functions make_noise and catch_mouse. The make_noise function should print different noises depending on the cat’s mood. The catch_mouse function returns true if the product of the cat’s weight and age is less than twice the speed of the mouse. Write the functions in the same order they appear inside the structure. Use implicit variable access.

You have attempted of activities on this page