Thread: C++ References
View Single Post
  #1  
Old 05-09-2008, 01:30 AM
.BZU.'s Avatar
.BZU. .BZU. is offline


 
Join Date: Sep 2007
Location: near Govt College of Science Multan Pakistan
Posts: 9,693
Contact Number: Removed
Program / Discipline: BSIT
Class Roll Number: 07-15
.BZU. has a reputation beyond repute.BZU. has a reputation beyond repute.BZU. has a reputation beyond repute.BZU. has a reputation beyond repute.BZU. has a reputation beyond repute.BZU. has a reputation beyond repute.BZU. has a reputation beyond repute.BZU. has a reputation beyond repute.BZU. has a reputation beyond repute.BZU. has a reputation beyond repute.BZU. has a reputation beyond repute
lectures C++ References

C++ references allow you to create a second name for the a variable that you can use to read or modify the original data stored in that variable. While this may not sound appealing at first, what this means is that when you declare a reference and assign it a variable, it will allow you to treat the reference exactly as though it were the original variable for the purpose of accessing and modifying the value of the original variable--even if the second name (the reference) is located within a different scope. This means, for instance, that if you make your function arguments references, and you will effectively have a way to change the original data passed into the function. This is quite different from how C++ normally works, where you have arguments to a function copied into new variables. It also allows you to dramatically reduce the amount of copying that takes place behind the scenes, both with functions and in other areas of C++


Basic Syntax

Declaring a variable as a reference rather than a normal variable simply entails appending an ampersand to the type name, such as this "reference to an int"

Code:
int& foo = ....;


Did you notice the "...."? (Probably, right? After all, it's 25% of the example.) When a reference is created, you must tell it which variable it will become an alias for. After you create the reference, whenever you use the variable, you can just treat it as though it were a regular integer variable. But when you create it, you must intialize it with another variable, whose address it will keep around behind the scenes to allow you to use it to modify that variable.

In a way, this is similar to having a pointer that always points to the same thing. One key difference is that references do not require dereferencing in the same way that pointers do; you just treat them as normal variables. A second difference is that when you create a reference to a variable, you need not do anything special to get the memory address. The compiler figures this out for you:
Code:
int x; int& foo = x; // foo is now a reference to x so this sets x to 56 foo = 56; std::cout << x <<std::endl;


__________________
(¯`v´¯)
`*.¸.*`

¸.*´¸.*´¨) ¸.*´¨)
(¸.*´ (¸.
Bzu Forum

Don't cry because it's over, smile because it happened
Reply With Quote