title: Write and read object of class into and from binary file
body: <p>I try to write and read object of class into and from binary file in C++. I want to not write the data member individually but write the whole object at one time. For a simple example:</p>
  
  <pre><code>class MyClass {  
  public:  
       int i;  
  
       MyClass(int n) : i(n) {}   
       MyClass() {}  
  
       void read(ifstream *in)  { in-&gt;read((char *) this, sizeof(MyClass));  }  
       void write(ofstream *out){ out-&gt;write((char *) this, sizeof(MyClass));}  
  };  
  
  int main(int argc, char * argv[]) {  
       ofstream out("/tmp/output");  
       ifstream in("/tmp/output");  
  
       MyClass mm(3);  
       cout&lt;&lt; mm.i &lt;&lt; endl;  
       mm.write(&amp;out);  
  
       MyClass mm2(2);  
       cout&lt;&lt; mm2.i &lt;&lt; endl;  
       mm2.read(&amp;in);  
       cout&lt;&lt; mm2.i &lt;&lt; endl;  
  
       return 0;  
  }
  </code></pre>
  
  <p>However the running output show that the value of mm.i supposedly written to the binary file is not read and assigned to mm2.i correctly</p>
  
  <pre><code>$ ./main   
  3  
  2  
  2  
  </code></pre>
  
  <p>So what's wrong with it?</p>
  
  <p>What shall I be aware of when generally writing or reading an object of a class into or from a binary file?</p>