Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

differences between *ptr and &ref

Status
Not open for further replies.

javaguy1

Programmer
May 14, 2003
136
0
0
US
can anyone explain how pointers are different from references.
 
There are many differences. One of the most significant ones is that you can use the delete operator on a pointer… even if you shouldn’t.
Code:
int* pint = new int;
delete pint;             // fine
int n = 10;
pint = &n;
delete pint;             // not so fine but compiles (runtime error)
int j = 12;
int& k = j;              // references same memory as "j"
delete k;                // compile error

-pete
 
Also, pointers can be reassigned, whereas references must be assigned when they are declared and cannot be reassigned.
 
Reference is an alternative name(alias) to an object whereas a pointer points to an object.
The most popular use of references is in the case of functions where U pass function parameters by reference.

For instance,
int main(){
int n;
.....
funct(n);
cout << n;
.....
return 0;
}

void funct(int &k){ //equivalent to int &k = n;
k = 1;
......
}

k here is just another name for the object n.

int *k = &p; // pointer.
//k is of type int* and stores the address
int &k = n; // reference.
// k is n renamed for that scope
// k is of type int NOT int*

int *pint; // only declares the pointer variable pint
pint = new int; //dynamically allocates memory to it.That is why a delete on it is justified.
delete pint; //fine

This coupled with the behaviours mentioned above should differentiate pointers and references.

Hope this helps.








 
The world would be a whole lot better if people saw it this way:
- If I get a reference, the variable-provider has to ensure the instance exist during my entire execution and is responible for the variable, I'm just borrowing it.
- If I get an auto-pointer, I take ownership and delete it when I'm finished.
- Passing pointers should be avoided, and only done if it is absolutely necessary (for example if the parameter is optional, you cant have a reference to something that's NULL).

These views are unfortunately not always the case (take MFC for example, where pointers get passed around quite irresponsibly).

/Per
[sub]
if (typos) cout << &quot;My fingers are faster than my brain. Sorry for the typos.&quot;;
[/sub]
 
thanks to all of you, that helped a lot.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top