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.
foo()
, is a == *ptr && a == 1
?bar()
, is b == ptr
?bar()
, is &b == &ptr
?new int(1)
) of ptr
stored 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?
- When the control is inside
foo()
, isa == *ptr && a == 1
?
Yes. The parameter a
is copy-initialized from the argument *ptr
, its value would be same as *ptr
, i.e. 1
.
- When the control is inside
bar()
, isb == ptr
?
Yes. The parameter b
is copy-initialized from the argument ptr
, its value would be same as ptr
.
- When the control is inside
bar()
, is&b == &ptr
?
No. They're independent objects and have different address.
- If your answer to Q.3 was false then is there even anything as a call-by-reference in C++?
Yes. You can change it to pass-by-reference.
int bar(int *&b);
Then the parameter b
would bind to the argument ptr
, it's an alias of ptr
; then &b == &ptr
is true.
At last,
Are pointers passed by value in C++?
Yes, they're passed by value themselves. The logic is the same as foo
as you noticed.
Would you comment on whether
class_name* &b
is useful in any scenario?
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.
int bar(int *&b) {
b = ...; // make b pointing to anything else
// the orginal pointer argument being passed gets changed too
}
Unless you use the reference specifier &
everything is passed by value.
In the case of bar
the value of the variable ptr
itself is copied into the local argument variable b
. As such changes to b
(like b = some_other_pointer
) is local to the bar
function only, the variable ptr
will not be changed.
You can use pointers to emulate pass by reference, and this is commonly used in C.
For example inside bar
if we did *b = 5;
that would change the value of *ptr
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With