Originally Posted by Varun95
I am new to C++. I don't understand the difference between passing string to a function as a const reference and without the use of const reference.
First let's go over what the
(reference) key words are and do. The const keyword prevents and operation or function from modifying the variable, in your case the string, that has the const keyword attached to it. This can be helpful when you're passing strings into functions. There will be times when you don't want a function to modify the contents of your string variable, so you can put const in front of the variable name.
void showValues ( const string name)
//Code that does stuff with your string variable
See how I put the constin front of the name variable? Now if I write code that tried to modify the variable, I'd get an error at compilation time that wouldn't allow me to build the program. You might be wondering why this is important to do
. Well if you build a program for a company and then five years later you leave that company and a new programmer has been given the task of updating your code, they'll need this. They won't be as familiar with your code as you were because you created it. Without the const they might write a function that edits the string even though you don't want what's in that string to be edited. It must stay constant so you add a const.
Now for the & or also known as the reference symbol. When you put the & symbol in front of a variable you've turned that variable into a reference variable
. When you do that it means that when it's used as a parameter it gives the function access to the original argument. Any changes made to the reference variable are actually performed on the argument referenced by the variable.
Now to be honest I am not 100% sure when you'd pass a string by const reference, since the idea of a reference variable is to change the contents of the variable and the const is to keep the contents of a variable the same
. There is sort of a similar application later on in C++ when you're talking about pointers and classes, but I think that's above your head for now. If you could tell me what you've been doing in class it would help me understand where you're coming from. Cheers