Disadvantages of references in Cpp

References can not be re initialized. They always refer to first referent.
 Reference arithmetic is not allowed.  Operation effects on actual referent. 
#include<iostream>
using namespace std;
int main()
{
int i=10;
int& j = i;
int & k =j;

cout<<"i: "<<i<<endl;
cout<<"j: "<<j<<endl;
cout<<"k: "<<k<<endl;

cout<<"&i: "<<&i<<endl;
cout<<"&j: "<<&j<<endl;
cout<<"&k: "<<&k<<endl;

//reference once initialized can not be reinitialed. point to first referent only.
int m=10;
int n=20;
int &x=m;
cout<<"x="<<x<<endl;//10
x=n;//this is not reassignment. actually its modifying value of m using x. this can be verified taking address of m and x as both would be same.
cout<<"x="<<x<<endl;//20
cout<<"m="<<m<<endl;//m gets modified to  20 now

cout<<"&x="<<&x<<endl;//0x7fff9671caf0
cout<<"&m="<<&m<<endl;//0x7fff9671caf0

//reference arithmatic is not allowed
int a=10;
int b=20;
int& ar=a;
cout<<"a="<<a<<endl;//10
cout<<"ar="<<ar<<endl;//10
ar++;//referant gets incremented not reference
cout<<"a="<<a<<endl;//11
cout<<"ar="<<ar<<endl;//11

return 0;
}
/*
i: 10
j: 10
k: 10
&i: 0x7fffee78603c
&j: 0x7fffee78603c
&k: 0x7fffee78603c
x=10
x=20
m=20
&x=0x7fffee786040
&m=0x7fffee786040
a=10
ar=10
a=11
ar=11

*/

No comments:

Post a Comment