Alias or Reference Variable in C++





A reference, like a pointer, stores the address of an object that is located elsewhere in memory. Unlike a pointer, a reference after it is initialized cannot be made to refer to a different object or set to null.

  • 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.

  • C++ reference variable is an alias or another-name of already existing variable.

  • Reference variable is declared by using & operator.

  • References are like constant pointers that are automatically dereferenced.

  • Reference variable must be initialize at the time of declaration.

Syntax:


type &newName = existingName;
   OR
type& newName = existingName;
   OR
type & newName = existingName;
                   
for e.g.
int x = 20;
int & ref = x;

Code Example:

#include<iostream>
using namespace std;
int main() {
int x = 20;
int &r = x;
cout<<"x = "<< x<< endl;
cout<<"r = "<< r<< endl;
r = 50;
cout<< endl;
cout<<"x = "<< x<< endl;
cout<<"r = "<< r<< endl;
return 0;
}

NOTE: There is no need to use * to dereference a reference variable.


OUTPUT:
x = 20
r = 20

x = 50;
r = 50


Pointers vs References:

Reference and pointer have some similarities like:

1. Both can be used to change local variables of one function inside another function.

2. Both of them can also be used to save copying of big objects when passed as arguments to functions or returned from functions.

Despite of having some similarities, there are following differences between pointers and references are:

S.NoPointersReferences
1. The pointer variables are declared by using * ( astric ) symbol.
Syntax:
type *var;
for e.g, int *p;
The reference varaibles are declared by usung & ( and ) symbol.
Syntax:
type & var = value;
for e.g, int & r = x;
2.A pointer can be declared as void.A reference can never be void.
3.The pointer variables hold the address of existing variable. The reference variables are just create the another name for existing variable.
4.The pointer variables occupy the separate memory space to hold address. The reference variables represent the same memory space with new name.
5. The pointer variables may contain NULL value. The reference variable can't be NULL.
6. The pointer variables can be declared without initialization. The reference variables must be initialized at the time of declaration.
7. The pointer variables can be re-initialize after declaration. Re-initialization of the reference variables are not allowed.

References in Function:

You can use references in two ways:
1. Function argument list and
2. Function return value.

You already know how to implement call by reference concept using pointers. Here is another example of call by reference which makes use of C++ reference:

Example:

Using References as Function Parameter :

When you use reference in argument list, you must keep in mind that any change to the reference inside the function will cause change to the original argument outside of the function.
#include<iostream>
using namespace std;
//function declaration
void swap(int &,int &);
int main() {
int x = 10, y =20;
cout<<"Before Swapping:\n";
cout<<"X = "<< x;
cout<<" Y = "<< y;
//function call
swap(x,y);
cout<<"\nAfter Swapping:\n";
cout<<"X = "<< x;
cout<<" Y = "<< y;
return 0;
}
//function definition
void swap(int &a,int &b){
   int temp;
   temp = a;
      a = b;
      b = a;
}
OUTPUT:
Before Swapping:
X = 10 Y = 20
After Swapping:
X = 20 Y = 10

In the above example you can see that if you make changes in formal parameter it gets reflected in actual argument.

Reference as Return value from Function :

  • You can also return-value as reference.

  • In C++ program its easier to read and maintain by using references rather than pointers.

  • A C++ function can return a reference in the same way as it returns a pointer.

  • When a function returns a reference, it returns an implicit pointer to its return value.

#include<iostream>
using namespace std;
int & mySquare(int &);
int main() {
 int n = 4;
 cout<<"In main() &n: ";
 cout<<&n<< endl;//0x23fe44
 int & r = mySquare(n);
 cout<<"In main() &r: ";
 cout<<&r<< endl;//0x23fe44
 cout<< r<< endl; // 16
 cout<< n<< endl; // 16
 return 0;
}
 
int & mySquare(int & m) {
 cout<<"In mySquare(): ";
 cout<<&m<< endl;//0x23fe44
 m *= m;
 return m;
}
OUTPUT:
In main() &n: 0x23fe44
In mySquare():0x23fe44
In main() &r: 0x23fe44
16
16

You should not pass Function's local variable as return value by reference

When returning a reference, just be careful that the object being referred to does not go out-side of scope. So it is not legal to return a reference to local variable. But you can always return a reference on a static variable.

int& myFunc() {
 int q;
 return q; 
// Compile time error
 static int x;
 return x; 
// Safe, x lives outside this scope
}

Const Reference:

You can declare a reference as const, by this reference you can access /read the value of the variable whose reference is created, but you cannot modify the value;

#include<iostream>
using namespace std;

int main() {
 int n = 4;
 const int &r = n;
 cout<<"n = "<< r;//legal
 r = 10;//compile time error
 return 0;
}

Next topic is Environment Setup





 






Training For College Campus

We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies like
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.

Please mail your requirement at info@prowessapps.in


Projects For Students

Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.

Students can mail requirement at info@prowessapps.in


CONTACT DETAILS

info@prowessapps.in
(8AM to 10PM):

+91-9026070669 , +91-9451396824

© 2016, prowessapps.in, All rights reserved