title: Difference between returning reference vs returning value C++
body: <p>Question about why is it necessary at all to return a reference from a function.</p>
  
  <p>Following code behaves exactly the same, if we replace <code>int&amp;</code> with <code>int</code> in line9 and line16.</p>
  
  <p>Is it true in my example code, returning reference vs value doesnt matter? In what kind of example it will start to matter? </p>
  
  <p>In my mind, we cant return the reference of a local variable of the function, since the local variable will be out of scope for the caller. Therefore, it only make sense to return a reference of a variable that the caller can see (in scope), but if the caller of the function can see the variable, then it doesnt need to be returned(?) (or is this returning done for the sake of keeping the code neat and tidy?)</p>
  
  <p>Related link: <a href="https://stackoverflow.com/questions/13077979/is-returning-a-reference-ever-a-good-idea">Is returning a reference ever a good idea?</a></p>
  
  <pre><code>#include &lt;iostream&gt;
  using namespace std;
  
  class myClass{
  private:
      int val;
  public:
      myClass(int);
      int&amp; GetVal();
  };
  
  myClass::myClass(int x){
      val = x;
  }
  
  int&amp; myClass::GetVal(){
      return val;
  }
  
  int main()
  {
      myClass myObj(666);
      cout &lt;&lt; myObj.GetVal() &lt;&lt; endl;
      system("pause");
      return 0;
  }
  </code></pre>