top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the difference between a pointer and a reference?

+3 votes
1,263 views
What is the difference between a pointer and a reference?
posted Dec 29, 2014 by Emran

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

3 Answers

+1 vote

To make it simple there is no difference between them as far as i or u see the internal picture. It is just how compilers implements the two different statements int *x=&y and int &x=y.
But Now coming to concepts. There are whole bunch of difference between them. A pointer is a variable which holds the address of some other variable while a reference is an alias to some variable.

To get deeper understanding u can read article.
http://www.embedded.com/electronics-blogs/programming-pointers/4023307/References-vs-Pointers

answer Dec 29, 2014 by Prakash
Well explained Prakash, let me put my view point -

A pointer is a variable which holds the address of some other variable while a reference is an alias to some variable. On the implementation front it is implemented as const pointer which is implicitly dereferenced.
0 votes

Reference:

A reference must always refer to some object and, therefore, must always be initialized;

Pointer:

pointers do not have such restrictions. A pointer can be reassigned to point to different objects while a reference always refers to an object with which it was initialized.

answer Dec 30, 2014 by Emran
0 votes

OK, that covers the difference(s) between pointers and references. Now, why was reference created at all? What was the need when pointer was already there?

Mr. Bjarne Stroustrup introduced references in C++ to support operator overloading. Consider the following code fragment for subtracting 2 objects and storing it in 3rd:

a = &b - &c;

where a, b and c are the objects with an overloaded '-' operator. Isn't the syntax 'un-natural'? To make it more natural he have introduced references. With references in place, the above line becomes:

a = b - c;

Simple, isn't it? :)

Another thing that comes to my mind apart from this is, how ugly the copy constructors would have been without the presence of references.

Another reason I love C++ !!

answer Jul 16, 2016 by Upayan Dutta
...