title: accessing private members without using friend class
body: <p>I have a homework in which:</p>
  
  <p>we have this code:</p>
  
  <pre><code>#include &lt;iostream&gt;
  using namespace std;
  class Test {
      int x;
      char y;
  public:
      Test() :x(0), y(0) { ; }
  };
  int main() {
      Test t;
      //Do stuff!
      return 0;
  }
  </code></pre>
  
  <p>and without adding getters and setters or using friend class we have to read <code>x</code> and <code>y</code> and also change them.</p>
  
  <p>I searched and found these ways:</p>
  
  <p>if there was a <code>template</code> function in my class I could say:</p>
  
  <pre><code>class Test {
      int x;
      char y;
  public:
      Test() :x(0), y(0) { ; }
      template&lt;typename T&gt;
      void do_something() {//not necessarily void function
          //Do some stuff 
      };
  };
  
  class a;
  // My specialization.
  template &lt;&gt;
  void Test::do_something&lt;a&gt;() {
      cout &lt;&lt; x &lt;&lt; endl;
      cout &lt;&lt; y &lt;&lt; endl;
      // getting data 
      x = 5;
      y = 'a';
      // changing data
      cout &lt;&lt; x &lt;&lt; endl;
      cout &lt;&lt; y &lt;&lt; endl;
      // getting data after changes we made
  }
  
  int main() {
      Test t;
      t.do_something&lt;a&gt;();
      return 0;
  }
  
  </code></pre>
  
  <p>and also the method, which I think is this question answer, is using pointers.</p>
  
  <p>like this:</p>
  
  <pre><code>class Test {
      int x;
      char y;
  public:
      Test() :x(0), y('0') { ; }
  };
  int main() {
      Test t;
      int* ptr = (int*)&amp;t;
      cout &lt;&lt; "x = " &lt;&lt; *ptr &lt;&lt; " y = " &lt;&lt; (char)*(ptr + 1) &lt;&lt; endl;
      *ptr--;
      //getting data
      *ptr = 12;
      ptr++;
      *ptr = 65;
      //changing data
      ptr--;
      cout &lt;&lt; "x = " &lt;&lt; *ptr &lt;&lt; " y = " &lt;&lt; (char)*(ptr + 1) &lt;&lt; endl;
      //getting data after changes we have made
      return 0;
  }
  </code></pre>
  
  <p>or using <code>reinterpret_cast</code> and pointers:</p>
  
  <pre><code>struct pointer {
      int x;
      char y;
  };
  
  class Test {
      int x;
      char y;
  public:
      Test() :x(0), y('0') { ; }
  };
  int main() 
  {
      Test t;
  
      pointer* p = reinterpret_cast&lt;pointer*&gt;(&amp;t);
      cout &lt;&lt; "X = " &lt;&lt; p-&gt;x &lt;&lt; " Y = " &lt;&lt; p-&gt;y &lt;&lt; endl;
      //getting data
      p-&gt;x = 5;
      p-&gt;y = 'a';
      //changing data
      cout &lt;&lt; "X = " &lt;&lt; p-&gt;x &lt;&lt; " Y = " &lt;&lt; p-&gt;y &lt;&lt; endl;
  
      //getting data from class after changing them with pointers
      return 0;
  }
  </code></pre>
  
  <p>my questions are:</p>
  
  <ol>
  <li>is such thing possible in other object oriented languages?</li>
  <li>does this mean access modifiers are useless?</li>
  <li>and is there anything we can do to prevent such thing to happen?</li>
  </ol>