Moeed Shahid
Moeed Shahid

Reputation: 21

Pointers in c++ pass by value/reference

like simple variables ,the pointer variables can also be used as a Value parameter or Reference parameter in functions..... but as the pointer variables are used 2 hold memory location or content of memory location then what more difference will it make if the pointer variable is used either as Value or as Reference parameter????

Upvotes: 2

Views: 3496

Answers (4)

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81674

If function A passes a pointer P by reference to another function B, then B can make P point to a different location in memory, and A will see that change. If, on the other hand, A passes P by value, then B can only change the contents of the memory that P points to. A will see changes to that memory, but P will never point to a different spot in memory when B returns.

Upvotes: 9

parapura rajkumar
parapura rajkumar

Reputation: 24403

The small example illustrates the need to pass a pointer by reference

//pass by value
void InitString1( char* buf )
{
    buf = new char[5];
}

//pass by reference
void InitString2( char*& buf )
{
    buf = new char[5];
}

int main()
{
    char* buffer = 0;
    InitString1( buffer);
    //buffer is still null and memory leaks
    delete [] buffer;

    InitString2( buffer );
    //buffer will be assigned correctly
    delete [] buffer;

    return 0;
}

Upvotes: 4

Robᵩ
Robᵩ

Reputation: 168596

#include <iostream>
void passByValue(int* p) {
  p = new int;
}
void passByReference(int*& p) {
  p = new int;
}
int main() {
  int *p1 = 0;
  int *p2 = 0;
  passByValue(p1);
  passByReference(p2);
  std::cout << p1 << "\n";
  std::cout << p2 << "\n";
}

Consider the above program. The first line will always print zero, meaning that main's p1 variable was not updated by the call to passByValue. In contrast, p2 was updated by the call to passByRefernce.

Upvotes: 0

NPE
NPE

Reputation: 500167

The difference is as follows:

  1. if you pass the pointer by value, any changes to the pointer made by the callee will not be visible to the caller;
  2. if you pass the pointer by reference, any changes to the pointer made by the callee will be visible to the caller.

Here, I am talking about the value of the pointer itself (i.e. where it points), and not about the value of the pointed-to object.

Upvotes: 6

Related Questions