"Right now I am stuck, trying to understand call by reference methodology."
When you pass-by-value, a copy of the variable is made for the function, so when you change the value of the variable in the function, the changes are made to the copy not the original variable, so when the function ends, the original variable remains unchanged.
example:
Code:
#include <iostream>
using namespace std;
void add2(int a)
{
a = a + 2;
}
int main()
{
int a = 10;
cout<<a<<endl;
add2(a);
cout<<a<<endl;
return 0;
}
output:
10
10
When you pass-by-reference, the reference isn't copied, so when you change the value of the variable in the function, it changes the original value. Pointers are kind of a hybrid. The address in a pointer variable is copied for the function, so it's passed by value, and if you try to change the value of the variable, i.e. the address, you are only changing the copy, so when the function ends the original address stored in the pointer will be the same. However, if instead of changing the address stored in the pointer, you change the value of what the pointer points to, it permanently changes the value AT the address stored in the pointer even though the address stays the same.
examples:
Code:
#include <iostream>
using namespace std;
void add2(int& r)
{
r = r + 2;
}
int main()
{
int a = 10;
cout<<a<<endl;
int& r = a;
add2(r);
cout<<a<<endl;
return 0;
}
output:
10
12
Code:
#include <iostream>
using namespace std;
void add2(int* p)
{
*p = *p + 2;
int number;
p = &number; //attempt to change the original address stored in p
}
int main()
{
int a = 10;
cout<<a<<endl;
int* p = &a; //p, a pointer to an int, equals the address of a
add2(p);
cout<<*p<<endl;
return 0;
}
output:
10
12