Saturday, February 20, 2016

[C++] Reference & V.S. pointer *

Reference is an alias of some variable., it doesn't take space in memory.
Pointer is the address of some variable.

Use reference wherever you can, pointers wherever you must.

When you Define:

int a=1;   int *p=&a;
int a=1;   int &b=a;

Pointer can be const but not reference

Pointer can have many levels : **p but not reference

Pointer's value can be NULL, but reference cannot be , a reference should be initialize when defined.

Pointer's value can be changed, but not reference

sizeof(reference) gives back the size of the object, but sizeof(pointer) gives the size of the pointer not the object.

Use reference as a parameter of method :
void method(A & ra)
void method(A * pa)
The same effects as passing a pointer :
1we can do the operations on the object by using  this reference/ pointer
2 will not make a copy of this object in memory
Differences :
1 in fact, when we use pointer as input parameter, we use exactly the value-passing, just we pass the address as the value:
void test(int *p)
{
  int a=1;
  p=&a;
  // ---> p points to the value of a(1) in memory
}

int main(void)
{
    int *p=NULL;
    test(p);
    // ---> p points NULL, because test take the value of p, just an address value-passing
    return 0;
}

but reference is different, we do not copy any thing. 
void test(int *&p)//input is the reference of the value's point (a reference to the value's address)
{
  int a=1;
  p=&a;
  // ---> p is a reference, so here we change the p so we change the p in the main to a new address with value 1    
}

int main(void)
{
    int *p=NULL;
    test(p);
    // ---> p points 1, because test take the reference of the pointer
    return 0;
}


No comments:

Post a Comment