Question about code in a tutorial series

The question is about something near the beginning (about 2 minutes in)

http://www.youtube.com/watch?v=GoMNA4dYXvE

I was wondering why he made made T constant and what that does for the code.
void set_element(int i, const T & newval
Last edited on
Comparing passing by value, passing by reference and passing by constant reference:
1
2
3
4
5
6
7
8
9
10
11
//Pass by value
 void set_element(int i, T newval)
//Create a copy of the object. If the object is complex and requires lots of data, passing by value will slow down the program

//Pass by reference
void set_element(int i, T& newval)
//Create an alias name of the object to access it directly. Saves runtime but does not guarantee that the referenced object will not be modified

//Pass by constant reference
void set_element(int i, const T& newval)
//Save runtime by directly accessing object. However, const qualifier ensures object will not be modified in any way by the function. 
There are times when you will not want to modify the passed object. For example, if you overload operators like +, -, *, etc. the return value is a new object without changing the parameters. To be on the safe side for functions that aren't going to modify its referenced parameters, use const.

newval = oldval
This will be illegal if newval is constant. Constant variables are not allowed to be changed.
Usually if the parameter is named something similar to "new value," the function is probably going to do something akin to this:
oldvariable = newval.Getvariable()

However, if the purpose of the function is to change things in the parameter, then you would use reference without the const qualifier.
Thank you.
Last edited on
Topic archived. No new replies allowed.