Here is my simple demostration of Call by Reference
to pointer in C++:
#include <iostream>
using namespace std;
void myMethod(int* &x) {
int t = 4;
int* pt = &t;
cout << "Address of t: " << pt << endl;
cout << "Value of t: " << *pt << endl;
x = pt;
cout << "Address of x: " << x << endl;
cout << "Value of x: " << *x << endl;
}
int main() {
int y = 5;
int* py = &y;
cout << "Address of y: " << py << endl;
cout << "Value of y: " << *py << endl;
myMethod(py);
cout << "Address of y after method: " << py << endl;
cout << "Value of y after method: " << *py;
return 0;
}
Output:
Address of y: 0x7ced454457cc
Value of y: 5
Address of t: 0x7ced4544579c
Value of t: 4
Address of x: 0x7ced4544579c
Value of x: 4
Address of y after method: 0x7ced4544579c
Value of y after method: 31205
I am passing the reference of the pointer to y
as an argument to the method myMethod()
. In the method, the passed reference is assigned a new pointer to t
, which in turn reassigns the pointer to y
i.e., py = pt
. Hence, after the method, when the pointer to y
is printed, it prints the correct pointer which is the pointer to t
. So, if we now print the dereferenced value of pointer to y
, it should print the value 4
. However, it prints some random number.
Why the Value of y after method
is some random number, and not equal to 4
?