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?
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.
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.
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.
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.
Both these can be advantages or disadvantages, depending on the situation.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With