By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,983 Members | 1,717 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 431,983 IT Pros & Developers. It's quick & easy.

What is the requirement of references in C++?

P: 12
Why do we need references in C++ when we can accomplish the same task with pointers?
Putting it in other words:
What are the advantages of using references over pointers?

How actually is passing using references in C++ is faster and efficient than passing values using pointers?
Aug 27 '10 #1
Share this Question
Share on Google+
3 Replies


weaknessforcats
Expert Mod 5K+
P: 9,197
References are passed as pointers. The compiler will de-reference the pointer for you.

The advantage of references over pointers is that when you use pointers that you dereference yourself you will at some point screw up. The compiler never screws up.

Second, studies have shown that member syntax is easy to use by programmers but they trip over pointer sytax:

Easy:

Expand|Select|Wrap|Line Numbers
  1. int a = 10;
  2.     fx(a);
  3.  
  4. void fx(int& arg)
  5. {
  6.    arg = 20;
  7. }
Not so easy:

Expand|Select|Wrap|Line Numbers
  1. int a = 10;
  2.     fx(&10);
  3.  
  4. void fx(int* arg)
  5. {
  6.     *arg = 20;
  7. }
Third, a function argument that uses an object requires that a copy of the object by made. That is, the copy constructor must be called. To avoid the copy, you use pointers and pass the address of the object and this gets you the "not so easy" case. Using a reference avoids the copy and get you the "easy to use" case.

Fourth, you use references as function arguments. Nowhere else are you to use references.

Fifth, you use a reference argument if the function does not need to switch to another object. You can't change a reference to refer to another object. If your function needs to change the object, then you use a pointer.

Sixth, review your code. If the function has a pointer argument and never changes the address in the pointer, then change the argument to a reference. You will find this eliminates 90% of the pointers in your code.
Aug 27 '10 #2

100+
P: 542
Well there you go!.....and here I was, previously believing that a reference was simply another name for a declared variable full stop.
Aug 30 '10 #3

Expert 100+
P: 2,398
Not so easy indeed!
Note the change to the argument when fx is called.
Expand|Select|Wrap|Line Numbers
  1. int a = 10; 
  2.     fx(&a); 
  3.  
  4. void fx(int* arg) 
  5.     *arg = 20; 
Aug 30 '10 #4

Post your reply

Sign in to post your reply or Sign up for a free account.