A reference is an implicit pointer
* Acts like another name for a variable
* Can be used in three ways
* A reference can be passed to a function
* A reference can be returned by a function
* An independent reference can be created
* Reference variables are declared using the & symbol
Example: void f(int &n);
Unlike pointers, once a reference becomes
associated with a variable, it cannot refer to
other variables
Advantages
1. The address is automatically passed
2.Reduces use of ‘&’ and ‘*’
3.When objects are passed to functions using
references, no copy is made
Hence destructors are not called when the
functions ends
Eliminates the troubles associated with
multiple destructor calls for the same object
Running Codes
Using pointer:
void f(int *n) {
*n = 100;
}
void main() {
int i = 0;
f(&i);
cout << i; // 100
}
Using reference :
void f(int &n) {
n = 100;
}
void main() {
int i = 0;
f(i);
cout << i; // 100
}
http://en.wikipedia.org/wiki/Reference_%28C%2B%2B%29void f(int *n) {
*n = 100;
}
void main() {
int i = 0;
f(&i);
cout << i; // 100
}
Using reference :
void f(int &n) {
n = 100;
}
void main() {
int i = 0;
f(i);
cout << i; // 100
}
No comments:
Post a Comment