Possible Duplicate:
C++: When to use References vs. Pointers
Could operator overloading have worked without references?
I couldn't help it, but this fundamental question was on my mind: why does C++ have references when you could do with pointers just as well?
I know that in certain situations they are slightly safer and more often than not they make the code prettier, but technically there is no difference, right? So are there any situations where I couldn't do with a pointer and a reference is a must?
I would like to see specific examples of when using references is unavoidable.
Disclaimer:
I haven't found any answers to this on StackOverflow, this is not a question about the differences in syntax. I am wondering why the C++ language introduced references in the first place.
Pointers: A pointer is a variable that holds memory address of another variable. A pointer needs to be de referenced with * operator to access the memory location it points to.
References are used to refer an existing variable in another name whereas pointers are used to store address of variable. References cannot have a null value assigned but pointer can. A reference variable can be referenced by pass by value whereas a pointer can be referenced but pass by reference.
The main advantages of references are that they always contain a valid value, are cleaner than pointers, and support polymorphism without needing any extra syntax. If none of these advantages apply, there is no reason to prefer a reference over a pointer.
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.
pass-by-reference
or return-by-reference
.const
)References can bind to temporary objects. To create a temporary pointer, you'd need to free it inside the method you pass it to. But you can't tell if it's a temporary or not inside.Operator overloading. Using pointers for "passing via reference" would give you unacceptable syntax.
If you have a pointer as a parameter, you have to check if it is NULL. With references, you do have to make that check. Here is why there is references in C++ from the man himself - http://www.stroustrup.com/bs_faq2.html#pointers-and-references
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