Thread: c++ basics
View Single Post
  #2 (permalink)  
Old July 10th, 2017, 02:37 PM
Eureka117 Eureka117 is offline
Registered User
 
Join Date: Jul 2017
Posts: 3
Thanks: 0
Thanked 2 Times in 1 Post
Default

Quote:
Originally Posted by Varun95 View Post
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
Code:
const
and
Code:
&
(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.
ex:
Code:
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
Reply With Quote
The Following 2 Users Say Thank You to Eureka117 For This Useful Post:
jimneal (September 13th, 2019)