const and inout Member Functions

Get to learn about const and inout member functions in this lesson.

const member functions

Some member functions do not make any modifications to the object that they are called on. An example of such a function is toString():

struct TimeOfDay { 
// ...
    string toString() {
        return format("%02s:%02s", hour, minute); 
    }
// ...
}

Since the whole purpose of toString() is to represent the object in a string format anyway, it should not modify the object.

A member function that does not modify the object is declared by the const keyword after the parameter list:

struct TimeOfDay { 
// ...
    string toString() const {
        return format("%02s:%02s", hour, minute); 
    }
}

That const guarantees that the object itself is not going to be modified by the member function. As a consequence, the toString() member function is allowed to be called even on immutable objects. Otherwise, the struct’s toString() could not be called:

Get hands-on with 1000+ tech skills courses.