title: Why can I expose private members when I return a reference from a public member function?
body: <p>In the code snippet, I am able to access the private member variable outside the class scope. Though this should never be done, why is it allowed in this case? Is it a bad practice to receive a returned private variable by reference ? </p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;cstdlib&gt;
  
  class foo
  {
      int x;
      public:
          foo(int a):x(a){}
          int methodOne() { return x; }
          int&amp; methodTwo() { return x; }
  };
  
  int main()
  {
      foo obj(10);
      int&amp; x = obj.methodTwo();
      x = 20;              // With this statement, modifying the state of obj::x
  
      std::cout &lt;&lt; obj.methodOne();
      getchar();
      return 0;
  }
  </code></pre>
  
  <p>And regarding this method, what does the return type convey ?  And also when should I have return type of this kind ?</p>
  
  <pre><code>int&amp; methodTwo() { return x; }
  </code></pre>
  
  <p><strong>PS:</strong> I am sorry if the subject line is vague. Can someone change it to the content relevant here. Thanks. </p>