Pass by Reference [RESOLVED]
Hi,
I found this as a sample Function from an exercise.
Code:
int search(const tvector<Student>& list, const string& idnum);
And I was wondering, is there any difference if the function was declared as
Code:
int search(const tvector<Student> &list, const string &idnum);
What does the ampersand ( & ) means in the 1st code?
Thanks.
Harddisk
Re: i'll try to help on that
Quote:
Originally posted by Aragorn
Now, when you have const &i, it means a constant pointer to (address of...) i, which doesn't mean a constant value of i.
Hope i made sense... and were right!
;)
Not exactly. I think you all get confused if you go on like this.
First, dont' mix up pointers and references. They are used for the same purposes mostly, but there are fundamental differences.
1. References are always constant, you can't change a reference to point to something else, also a reference allways points to something, whereas a pointer can point to 0. (which means it's a null pointer)
2. References name access their contents, not their pointer value. ie i=5 changes the objects that i is pointing towards. Pointers need you to dereference to access their contents, using * dereferencing operator.
Second a constant reference is pointing to a non-mutable object, that is the compiler has to watch out to not change the contents of the reference.
Passing a constant reference is an agreement for the function that it won't change the object passed. This way you eliminate lots of debugging time if there's something wrong with the function. If the type of which object you passed constant has functions, they are able to change the value on the object, so therefore you can declare a function constant by putting const after the declaration of the functions parentesis. The function therefore can only call const functions on the constant reference.
& operator is the addressof (refer) operator, you can use it to pass a object as a pointer, not reference, because & will return a pointer to the object you referer.