< Previous | Contents | Next >

Declaring Parameters as Constant

References

The function display() shows the contents of the heros inventory. In the functions header I specify one parametera constant reference to a vector of string objects named vec.

void display(const vector<string>& vec)

A constant reference is a restricted reference. It acts like any other reference, except you cant use it to change the value to which it refers. To create a constant reference, simply put the keyword const before the type in the reference declaration.

What does this all mean for the function display()? Because the parameter vec is a constant reference, it means display() cant change vec. In turn, this means that inventory is safe; it cant be changed by display(). In general, you can efficiently pass an argument to a function as a constant reference so its accessible, but not changeable. Its like providing the function read-only access to the argument. Although constant references are very useful for specifying function parameters, you can use them anywhere in your program.


Hin t

image

A constant reference comes in handy in another way. If you need to assign a constant value to a reference, you have to assign it to a constant reference. (A non-constant reference won’t do.)

image