reference sign ??

why is it okey to write this

1
2
  	const int &num=5;
	std::cout<<num<<std::endl;


and not okey to write this

1
2
        int& num=5;
	std::cout<<num<<std::endl;



and what does the first reference before the operator function ??

 
       const int & operator= ( const int & rhs) ;
Last edited on
Consider this short program:

1
2
3
4
5
6
7
8
9
10
#include<iostream>
using namespace std;

int main()
{
    int x = 7;
    int& num = x;
    num++;
    cout<<"x: "<<x<<"\n";
}

Output
 
x: 8


Num is a reference to (i.e. an alias of) x, so we managed to change the value of x by incrementing num. But would it be possible to do the same if int& num = 5? No! Hence any reference to 5 has to be a const reference since 5 cannot be changed using that reference. In actual fact 5 cannot be changed at all since it's a fixed number but if the reference were to some other object rather than an int of fixed value then it would be more appropriate to say that in this case the object cannot be changed using that reference since the reference is const.

Now for ... const int & operator= ( const int & rhs) ;

Here we have an overloading of operator = and the overloading method returns a reference to a const int. The reference return feature of the method is captured by the first &. However when you return references from functions you need to be careful that the referenced object's lifetime is not longer than the lifetime of the object that it references. This typically happens with local objects/variables that go out of scope when the function returns and in this case the function should return by value which is a copy of the object that will thus persist after the original object goes out of scope

Thank You ^_^ that was very helpful ..
Topic archived. No new replies allowed.