Member Function Example

Member functions are further explained using an example in this lesson.

We'll cover the following

increment() member function

Let’s define a member function that adds a duration to TimeOfDay objects.

Before doing that, let’s first correct a design flaw that we have been living with. We have seen in the structs chapter that adding two TimeOfDay objects in addDuration() is not a meaningful operation:

TimeOfDay addDuration(TimeOfDay start, 
                      TimeOfDay duration) {  // meaningless
    //...
}

What is natural to add to a point in time is duration? For example, adding the travel duration to the departure time would result in the arrival time.

On the other hand, subtracting two points in time is a natural operation, in which case the result would be a duration.

The following program defines a Duration struct with minute-precision and an addDuration() function that uses it:

Get hands-on with 1200+ tech skills courses.