Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are pointers passed by value in C++?

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.

  1. When the control is inside foo(), is a == *ptr && a == 1?
  2. When the control is inside bar(), is b == ptr?
  3. When the control is inside bar(), is &b == &ptr?
  4. 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)) 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?
like image 651
Twarit Waikar Avatar asked Nov 28 '22 21:11

Twarit Waikar


2 Answers

  1. When the control is inside foo(), is a == *ptr && a == 1?

Yes. The parameter a is copy-initialized from the argument *ptr, its value would be same as *ptr, i.e. 1.

  1. When the control is inside bar(), is b == ptr?

Yes. The parameter b is copy-initialized from the argument ptr, its value would be same as ptr.

  1. When the control is inside bar(), is &b == &ptr?

No. They're independent objects and have different address.

  1. 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.

EDIT

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
}
like image 71
songyuanyao Avatar answered Dec 24 '22 18:12

songyuanyao


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.

like image 29
Some programmer dude Avatar answered Dec 24 '22 18:12

Some programmer dude