title: c++ Read/Write class from/to binary file
body: <p>I need to write a class to a binary file, and then I need to read it back.</p>
  
  <p>I have <code>Triangle</code> and <code>BinaryFile</code> classes, and some other classes. I am not sure if I am writing incorrectly or reading incorrectly. An error occurs when reading.  After debugging, I think that it gets inappropriate data for my private variables. I will be very glad if someone can give me some advice on how to make it work properly.</p>
  
  <p>I wasn't sure if I should paste the whole code or not, so I will give you a short snippet of code.  Just in case, here is a download link for my source code:</p>
  
  <p><a href="https://my.pcloud.com/publink/show?code=XZJ7CYZbsLWLglqV5p83csijcEUTFqqpM3k" rel="noreferrer">https://my.pcloud.com/publink/show?code=XZJ7CYZbsLWLglqV5p83csijcEUTFqqpM3k</a></p>
  
  <p>I am a newbie in programming and I don't speak English very well, so I apologize in advance for my mistakes.</p>
  
  <pre><code>class Point
  {
  private:
      int x;
      int y;
  };
  
  class Figure
  {
  private:
      string name;
      string type;
  };
  
  class Triangle: public Figure
  {
  private:
      Point p1, p2, p3;
  };
  
  class BinaryFile
  {
  private:
      string FileName;
      fstream File;
  public:
      //...
      void AddNewFigure(istream&amp; stream)
      {       
          File.open(this-&gt;FileName, ios::binary | ios::app);
          if(!this-&gt;File)
          {
              cerr&lt;&lt;"File error &lt;"&lt;&lt;this-&gt;FileName&lt;&lt;"&gt;\n";
              exit(1);
          }
          Triangle fig;
          fig.MakeNewFigure(stream);
          File.write((char*)&amp;fig, sizeof(Triangle));
          File.close();
      }
  
      Triangle GetTriangle()
      {
          Triangle trig;
          Point p;
          string str(""); int x(0);
          File.open(this-&gt;FileName, ios::binary | ios::in);
          if(!this-&gt;File)
          {
              cerr&lt;&lt;"File error &lt;"&lt;&lt;this-&gt;FileName&lt;&lt;"&gt;\n";
              exit(1);
          }
          File.read((char*)&amp;trig, sizeof(Triangle));
          File.close();
          return trig;
      }
  };
  </code></pre>