Const recap

Const & references

int         returnValue()          { return 7; }
const int   returnConstValue()     { return 7; } 

int&        returnReference()      { static int value1=7; return value1; }
const int&  returnConstReference() { static int value2=7; return value2; }


int main()
{
  int a1  = returnValue();          a1 = 1; 
  int a2  = returnConstValue();     a2 = 1;
  
  int a3  = returnReference();      a3 = 1;  
  int a4  = returnConstReference(); a4 = 1;
  
  /* Block commented out
   Can't return a value to int& (to a reference)
  int& a5 = returnValue();
  int& a6 = returnConstValue();
  */
  
  int& a7  = returnReference();      a7 = 1;   // Assignment will change 'value1' in return reference
  
  /* Block commented out
  Assigning a const reference to a referene is not possibe
  int& a8  = returnConstReference();
  */
  
  const int& a9 = returnConstReference();     
  
}

Legend

 

           received by Value

           function's variable unchanged 

 

           Invalid. won't compile

 

           return to non-cost reference

           function's variable may change

 

           return to const reference 

           function's variable may change.

 

To experiment yourself. the source may be found in C++ Shell.

Const

By perplexedpigmy