0
C++
I want explanation about pass by reference
5 Answers
+ 2
reference is similar with pointer, the main difference is a reference will always pointing to something, while pointers can be 0
+ 8
=> When you pass a variable by value, a copy of original variable is created and any change made to the variable within the function will not affect the original one.Example:-
void increament(int a){
a = a+1;
}
int main(){
int a = 5;
increament(a);
cout<<a;
return 0;
}
#Output 5 not 6
=>When you pass a variable by reference, a reference to the original variable is passed and any change made to the variable within the function will affect the original variable.Example:-
void increament(int &a){
a = a+1;
}
int main(){
int a = 5;
increament(a);
cout<<a;
return 0;
}
#Output 6
##Note the & symbol in pass by reference.
+ 1
Well reference is not a variable, they don't have any allocated location on the memory like a variable
0
Reference is not similar to pointer because pointer is a variable while reference is not.
You can create a reference to pointer but you cannot create a pointer to reference
When you pass by reference, you are passing the actual object that wouldve been copied otherwise
0
Melle a reference is still a variable in C++, just not behaves exactly as a pointer variable, they are similar.
However the question is about passing a argument by reference in a function.
In this case the main difference is that you not have to worry if the reference is references to nothing (like a pointer can) and other small differences like you use '.' instead of '->'.
When pass by reference, compiler will pass a pointer of the object and will handle it same as pass by pointer. This is how it is able to pass the actual object without copy it