Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/articles/cpp-tutorials/)
-   -   Difference between Pointers and Reference in C++ (http://www.go4expert.com/articles/difference-pointers-reference-cpp-t5492/)

Shishir191 27Jul2007 17:36

Difference between Pointers and Reference in C++
 
Pointers and Reference looks similar but there are some difference between both of them.

POINTER

  1. Its not necessary to initialize the pointer at the time of declaration. Like
    Code:

     
    int a = 10;
    int *P = &a; //It is not necessary

    Another way is :
    Code:

    int a  = 10;
    int *P;
    P =  &a;

  2. You can create the array of Pointer.
  3. You can assign NULL to the pointer like

    Code:

    int *P = NULL; //Valid
  4. You can use pointer to pointer.

REFERENCE

  1. Its necessary to initialize the Reference at the time of declaration. Like
    Code:

    int &a = 10;
    int &a;  //Error here but not in case of Pointer.

  2. You can not create the Array of reference.
  3. You can not assign NULL to the reference like

    Code:

    int &a = NULL; //Error
  4. You can not use reference to reference.

shabbir 27Jul2007 18:31

Re: Difference between Pointers and Reference in C++
 
Nice differences.

Shishir191 27Jul2007 18:33

Re: Difference between Pointers and Reference in C++
 
Thanks.

kush_2207 14Aug2007 14:09

Re: Difference between Pointers and Reference in C++
 
good one.....but what would you say if i write in .NET or even in JAVA
FileStream fs; // (or using any other class)
What is FileStream -> a pointer or a reference ?
Can you elaborate it for other platforms ?

shabbir 14Aug2007 15:36

Re: Difference between Pointers and Reference in C++
 
In Java or C# everything is reference and there is nothing known as pointer.

kush_2207 14Aug2007 18:54

Re: Difference between Pointers and Reference in C++
 
Thank you sir.

kaustubh 15Aug2007 09:14

Re: Difference between Pointers and Reference in C++
 
Reference is the other name given to the same variable. Pointer is new variable created which can contain address of another variable.

Try an experiment

Code:

# include<iostream>
using namespace std;
int main()
{

int i = 90; // variable
int &j = i;  // reference
int *P;  //  pointer
P =&i;

cout<<endl<< "address of variable :i" <<&i;

cout<< endl << "address of reference: j" <<&j;
cout<<endl<<"address of pointer : P"<<&P;
return 0;
}
OUTPUT:
 address of variable i: i0012FEDC
address of reference j: 0012FEDC
address of pointer p: 0012FEE0

so you see the address of i and reference j is same , address of pointer P is different.

shal 8Sep2007 13:37

Re: Difference between Pointers and Reference in C++
 
nice one

zaka_d 10Sep2007 16:26

Re: Difference between Pointers and Reference in C++
 
In C++ a reference variable is internally implemented as a constant pointer, and that is why it is necessary to initiallize a reference variable during declaration... as it is treated as a constant variable (pointer) internally.

DaWei 10Sep2007 22:00

Re: Difference between Pointers and Reference in C++
 
That is incorrect, zaka. A reference is a second name (alias) for an object. You can't name something that doesn't exist, therefore you have to specify the object being aliased when you declare the reference. When a reference is passed as an argument, a copy of the objects address is passed. This is one fewer levels of indirection than when a pointer to the object is passed.

pritish 11Sep2007 11:50

Re: Difference between Pointers and Reference in C++
 
pointer is variable which holds the address of another variable ,another function and incomplete in C.
incomplete means ----------void *p;
it's a generic pionter ,we can not allocate memory by dynamically with this .
size of pointer is depending on the memory model.

Kailash 12Sep2007 12:46

Re: Difference between Pointers and Reference in C++
 
very appropriately describe the difference between pointer and reference. I find it very valuable

sashimi 23Nov2007 14:17

Re: Difference between Pointers and Reference in C++
 
In C#, the object of a Class

1. is a reference ? or
2. is a STACK to HEAP pointer ?

the objects shouldn't go into the HEAP ? :cool: if they are references of the class instances.

sreeramu 23Nov2007 17:21

Re: Difference between Pointers and Reference in C++
 
Thank you good difference...

sreeja 10Dec2007 15:05

Re: Difference between Pointers and Reference in C++
 
pointer is not necessary to initialize the pointer at the time of declaration and reference to initialize the Reference at the time of declaration .Ok thank you.

Shishir191 7Jan2008 19:08

Re: Difference between Pointers and Reference in C++
 
Quote:

Originally Posted by sreeja
pointer is not necessary to initialize the pointer at the time of declaration and reference to initialize the Reference at the time of declaration .Ok thank you.

Good

oogabooga 9Jan2008 05:03

Re: Difference between Pointers and Reference in C++
 
Quote:

Originally Posted by DaWei
When a reference is passed as an argument, a copy of the objects address is passed. This is one fewer levels of indirection than when a pointer to the object is passed.

A reference is (usually) exactly the same as a pointer, from
an implementation and performance point of view. They are,
in that sense, pure syntactic sugar. The only difference is
that in some cases a reference can be optimized away.
I'm not saying they are a bad thing, they're good for what
they are designed for. It's just incorrect to suggest that
they offer a performance advantage over pointers.

If you still disagree, consider this C++ and its assembly code
(from g++ using -S flag):

Code:

#include <iostream>
using namespace std;

void f( int i, int& r, int* p ) {
    ++i;
    ++r;
    ++*p;
}

int main() {
    int i = 0, r = 1, p = 2;
    cout<< i <<' '<< r <<' '<< p <<endl;
    f( i, r, &p );
    cout<< i <<' '<< r <<' '<< p <<endl;
}

I've condensed the assembly for brevity. ## comments are mine.
Code:

...
__Z1fiRiPi:  ## f's mangled name: Z1(arbitrary) f(our name) iR(int&) iP(int*) i(int)
pushl        %ebp
movl        %esp, %ebp       
incl        8(%ebp)          ## inc value at stack offset 8    (i)
movl        12(%ebp), %eax    ## load pointer at stack offset 12 (r)
incl        (%eax)            ## inc indirect (dereference)
movl        16(%ebp), %eax    ## same as for r                  (p)
incl        (%eax)
popl        %ebp
ret
...
movl        $0, -4(%ebp)      ## Load the variables with 0, 1, and 2.
movl        $1, -8(%ebp)      ## Note their constant addresses (stack offsets).
movl        $2, -12(%ebp)    ## i is -4, r is -8, p is -12 (relative to ebp)
...
leal        -12(%ebp), %eax  ## push p's address
pushl        %eax
leal        -8(%ebp), %eax    ## push r's address (same as for p)
pushl        %eax
pushl        -4(%ebp)          ## push i (value)
call        __Z1fiRiPi        ## call f
...


asadullah.ansari 11Jan2008 10:17

Re: Difference between Pointers and Reference in C++
 
You all are correct.
One main Difference is that Extra memory is taken by Pointer( Size depends on machine architecture i.e. 32-bit machine will be 32 bit size of pointer) But in case of reference is Only Alias for that object.

Some book written that reference is just like a constant pointer. But it's not correct. Just reference 's behabiour is like constant pointer.

asadullah.ansari 11Jan2008 10:18

Re: Difference between Pointers and Reference in C++
 
One More use of it is to cleanup Code in place of pointer.......

Shishir191 25Feb2008 15:11

Re: Difference between Pointers and Reference in C++
 
Quote:

Originally Posted by asadullah.ansari
One More use of it is to cleanup Code in place of pointer.......

Thanks to all.

lead.smart34 26Feb2008 18:17

Re: Difference between Pointers and Reference in C++
 
good info

crazytolearn57 26Feb2008 18:39

Re: Difference between Pointers and Reference in C++
 
good one

aisha.ansari84 5Mar2008 18:36

Re: Difference between Pointers and Reference in C++
 
Quote:

Originally Posted by DaWei
That is incorrect, zaka. A reference is a second name (alias) for an object. You can't name something that doesn't exist, therefore you have to specify the object being aliased when you declare the reference. When a reference is passed as an argument, a copy of the objects address is passed. This is one fewer levels of indirection than when a pointer to the object is passed.

i agree to it

Shishir191 7May2008 17:00

Re: Difference between Pointers and Reference in C++
 
Quote:

Originally Posted by aisha.ansari84
i agree to it

Thanks to All.

pavankumar.thati 10Jul2008 06:53

Difference between Pointers and Reference in C++
 
there is a class Date and a function
the function is non static

Date& and *this is same in representation and they are explain plzzzzzzz.........

Code:

class Date
{
              Date& add_year(int);
              Date& add_month(int);
              Date& add_day(int);
}
int main()
{
              Date a();
            a.add_year(1).add_month(2).add_day(2);
                return 0;
}
Date& Date::add_year(int n)
{
                  if(d==29&&m==2&&!leapyear(y+n)
                  {
                              d=1;
                              m=3;
                  }
                    y+=n;
                    return  *this;
}
Date& Date::add_month(int n)
{
                return *this;
}
Date& Date::add_day(int n)
{
              return *this;
}

Is this a valid one if then give me some explanation with examples.
plzzzzzzzzzzzzz...........

Darrelljones 28Jan2011 00:27

Re: Difference between Pointers and Reference in C++
 
A pointer can be re-assigned any number of times while a reference can not be reassigned after initialization.
A pointer can point to NULL while reference can never point to NULL
You can't take the address of a reference like you can with pointers
There's no "reference arithmetics" (but you can take the address of an object pointed by a reference and do pointer arithmetics on it as in &obj + 5).

As a general rule,

Use references in function parameters and return types to define attractive interfaces.
Use pointers to implement algorithms and data structures.

poornaMoksha 29Jan2011 19:05

Re: Difference between Pointers and Reference in C++
 
Shishir pointed out in the very first post of this discussion that " Its not necessary to initialize the pointer at the time of declaration". I think its not mandatory but still we should always make sure that a pointer is initialized to NULL whenever it is declared because :

Code:

int main()
{
    char *ptr;
    int retval = 0;
    retval = someFunc();
    if(retval)
        ptr = "I got some address";
    someOtherFunc(ptr);
}

void someOtherFunc(char *ptr)
{
    if(ptr)
    {
        // use ptr
    }
}

Now in the above code snippet, suppose the value of 'retval' is 0 which ensures 'ptr' does not get address of string "I got some address" and inside the function 'someOtherFunc' the condition 'if(ptr)' may well be true as ptr may be holding some garbage address which is non-null and hence when we use ptr we may well observe a crash as through 'ptr' the program would try to access the garbage address

kumarmannu 3Feb2011 14:48

Re: Difference between Pointers and Reference in C++
 
1. A pointer can be re-assigned any number of times while a reference can not be reassigned after initialization.
2. A pointer can point to NULL while reference can never point to NULL
3. You can't take the address of a reference like you can with pointers
4. There's no "reference arithmetics" (but you can take the address of an object pointed by a reference and do pointer arithmetics on it as in &obj + 5).

1) A pointer can be re-assigned:

int x = 5;
int y = 6;
int *p;
p = &x;
p = &y;
*p = 10;
assert(x == 5);
assert(y == 10);

A reference cannot, and must be assigned at initialization:

int x = 5;
int y = 6;
int &r = x;
A pointer needs to be dereferenced with * to access the memory location it points to, whereas a reference can be used directly. A pointer to a class/struct uses -> to access it's members whereas a reference uses a .

A pointer is a variable that holds a memory address. Regardless of how a reference is implemented, a reference has the same memory address the item it references.

References cannot be stuffed into an array, whereas pointers can be (Mentioned by user @litb)

kumarpyasa 1Mar2011 12:40

Re: Difference between Pointers and Reference in C++
 
Hello dear
Pointers and references are the different
1. pointers use the * and -> operators and references use .
2. A pointer can be re-assigned any number of times while a reference can not be reassigned after
initialization.
3.A pointer can point to NULL while reference can never point to NULL
4. You can't take the address of a reference like you can with pointers
5. There's no "reference arithmetics" (but you can take the address of an object pointed by a
reference and do pointer arithmetics on it as in &obj + 5).

alexsmth114 8Mar2011 12:10

Re: Difference between Pointers and Reference in C++
 
Really nice tutorial, thanks for sharing!!..

alexsmth114 11Mar2011 10:15

Re: Difference between Pointers and Reference in C++
 
Really nice comparison, useful post, keep them coming!!..

msdnguide 27May2011 20:04

Re: Difference between Pointers and Reference in C++
 
Reference is just an alias. Like a different name to same variable where as Pointer is the actual memory location where the variable is stored

sachin.magdum 29Jan2012 22:50

Re: Difference between Pointers and Reference in C++
 
Little curious about fourth difference. Can we really not create reference to reference?

int obj;
int & ref = obj;
int & ref_2 = ref; // although equivalent to int & ref_2 = obj;
// I agree that we do not have some thing like int & & ref_to_ref = ref;

------------------------------------------------------
1. There exists void pointers, but no void references.
2. Pointer is a variable, that has its own address. References are alias to some other variable, references do not have their own address.

sura 4Feb2012 22:02

Re: Difference between Pointers and Reference in C++
 
nice.


All times are GMT +5.5. The time now is 00:48.