Member Functions

You will learn about the member functions of structs and the special toString() member function.

Although this lesson focuses only on structs, most of the information in this lesson is applicable to classes as well.

When a struct or class is defined, a number of functions are usually also defined alongside it. We have seen examples of such functions in the earlier chapters: addDuration() and an overload of info() have been written specifically to be used with the TimeOfDay type. In a sense, these two functions define the interface of TimeOfDay.

The first parameter of both addDuration() and info() has been the TimeOfDay object that each function would operate on. Additionally, just like all of the other functions that we have seen so far, both of the functions have been defined at the module level, outside of any other scope.

The concept of a set of functions determining the interface of a struct is very common. For that reason, functions that are closely related to a type can be defined within the body of that type.

Defining member functions

Functions that are defined within the curly brackets of a struct are called member functions:

struct SomeStruct {
    void member_function(/* the parameters of the function */) {
        // ... the definition of the function ...
    }
    // ... the other members of the struct ...
}

Member functions are accessed the same way as member variables, separated from the name of the object by a dot:

object.member_function(arguments);

We have used member functions before when specifying stdin and stdout explicitly during input and output operations:

Get hands-on with 1400+ tech skills courses.