Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any advantage of using references instead of pointers in c++? [duplicate]

Possible Duplicate:
What are the differences between pointer variable and reference variable in C++?

For example, I have two functions that do the same thing:

int func(int &a)
{
   return a+1;
}

and

int func2(int *a)
{
   return *a+1;
}

What is the advantage of using func over func2 when calling any one of these functions?

like image 564
Kang Min Yoo Avatar asked Apr 28 '12 01:04

Kang Min Yoo


People also ask

Is it better to use pointer or reference?

References are usually preferred over pointers whenever you don't need “reseating”. This usually means that references are most useful in a class's public interface. References typically appear on the skin of an object, and pointers on the inside.

What is the significant advantages that you see in using reference instead of pointers?

Reference variables are cleaner and modish as compare to the pointers; they can also be used while passing in the function as arguments, known as call by references.

Are references more efficient than pointers?

It's much faster and memory-efficient to copy a reference than to copy many of the things a reference is likely to refer to. Pointers almost always point to data allocated on the heap. Pointers can be (and frequently are) null.

What is the advantage of reference variables over pointer variables?

There are many advantages of using reference variables over pointer variables such as: A reference variable does not consume any extra memory. It has the same memory address as the variable it refers to. While a pointer needs extra space for itself.


3 Answers

  • A reference cannot be assigned null directly, but a pointer can be.
  • A reference cannot be reassigned to point to something else, but a pointer can be.

Both these can be advantages or disadvantages, depending on the situation.

like image 104
Mark Byers Avatar answered Nov 14 '22 22:11

Mark Byers


Both of your functions are wrong. Since they don't modify the argument passed in, they should take them in as const, like this:

int func(const int &a)
{
    return a+1;
}

int func2(const int *a)
{
    return *a+1;
}

Now here's an advantage for references, I can pass rvalues into the reference version:

func(10);
func(func(func(10)));

I can't do that with the pointer version.

like image 23
Benjamin Lindley Avatar answered Nov 14 '22 22:11

Benjamin Lindley


The pointer is more flexible, it can also be predefined in the declaration like:

 int func2(int *a = nullptr);

Which does not work in your simple case but in many others it does.

The pointer may also more easily be used for other things, like storing in a list, typacasting it and other things.

And yes, the reference cannot be reassigned.

like image 41
HardCoder Avatar answered Nov 14 '22 23:11

HardCoder