Consider the following function definitions:
int foo(int a);
int bar(int *b);
int main()
{
int *ptr = new int(1);
foo(*ptr);
bar(ptr);
}
I need help clearing a few confusions I have.
- When the control is inside
foo(), isa == *ptr && a == 1? - When the control is inside
bar(), isb == ptr? - When the control is inside
bar(), is&b == &ptr? - If your answer to Q.3 was false then is there even anything as a call-by-reference in C++? It looks like the pointers were passed by value still but we have the contents (memory address to
new int(1)) ofptrstored in another variable now. Is this because in this case the ptr was copied and it was as if we had the case in Q.1 but the integer value happens to be a memory address?
Yes. The parameter
ais copy-initialized from the argument*ptr, its value would be same as*ptr, i.e.1.Yes. The parameter
bis copy-initialized from the argumentptr, its value would be same asptr.No. They're independent objects and have different address.
Yes. You can change it to pass-by-reference.
Then the parameter
bwould bind to the argumentptr, it's an alias ofptr; then&b == &ptris true.At last,
Yes, they're passed by value themselves. The logic is the same as
fooas you noticed.EDIT
Just as other non-pointer types being passed by reference, it's useful if you want to modify the pointer itself (not the pointee) in the function. e.g.