const ref Parameters

Learn about the const ref parameters and non-const member functions.

This lesson is about how parameters and member functions are marked as const so that they can be used with immutable variables as well.

Although the examples in this lesson use only structs, const member functions also apply to classes.

immutable objects

You have already seen that it is not possible to modify immutable variables:

immutable readingTime = TimeOfDay(15, 0);

readingTime cannot be modified:

readingTime = TimeOfDay(16, 0); // ← compilation ERROR 
readingTime.minute += 10; // ← compilation ERROR

The compiler does not allow modifying immutable objects in any way.

ref parameters that are not const

Parameters that are marked as ref can freely be modified by the function. Therefore, even if the function does not actually modify the parameter, the compiler does not allow passing immutable objects as that parameter:

/* Although not being modified by the function, 'duration' 
* is not marked as 'const' */
int totalSeconds(ref Duration duration) {
    return 60 * duration.minute; 
}
// ...
    immutable warmUpTime = Duration(3); 
    totalSeconds(warmUpTime); // ← compilation ERROR

The compiler does not allow passing the immutable warmUpTime to totalSeconds because that function does not guarantee that the parameter will not be modified.

const ref parameters

const ref means that the parameter is not modified by the function:

int totalSeconds(const ref Duration duration) {
    return 60 * duration.minute; 
}
// ...
immutable warmUpTime = Duration(3); 
totalSeconds(warmUpTime); // ← now compiles

Such functions can receive immutable objects as parameters because the immutability of the object is enforced by the compiler:

int totalSeconds(const ref Duration duration) { 
duration.minute = 7; // ← compilation ERROR
// ...
}

An alternative to const ref is in ref. As you will see in a later chapter, in means that the parameter is used only as input to the function, disallowing any modification to it.

int totalSeconds(in ref Duration duration) {
    // ...
}

Non-const member functions

As you have seen with the TimeOfDay.increment member function, objects can be modified through member functions as well. increment() modifies the members of the object that it is called on:

Get hands-on with 1400+ tech skills courses.