title: write an object to a binary file in c++
body: <p>I get confused when I wrote an object to a binary file in C++. When I wrote a string to a file, like this:</p>
  
  <pre><code>//write a string to a binary file
  ofstream ofs("Test.txt", ofstream::binary | ofstream::app);
  string foo = "This is a long .... string."
  ofs.write((char*)&amp;foo, sizeof(foo));
  ofs.close();
  </code></pre>
  
  <p>But it wrote something else(maybe a pointer) to the file rather than the string itself.</p>
  
  <p>When I wrote an object of a class(which has a string member), it worked.</p>
  
  <pre><code>// a simple class
  class Person {
  public:
      Person() = default;
      Person(std::string name, int old) : fullName(name), age(old) {}
      std::string getName() const { return this-&gt;fullName; }
      int getAge() const { return this-&gt;ID; }
  
  private:
      string fullName;
      int age;
  };
  
  int main()
  {
      std::ofstream ofs("Test.txt", std::ofstream::binary | std::ofstream::app);
      Person p1("lifeisamoive", 1234);
      ofs.write((char*)&amp;p1, sizeof(Person));
      ofs.close();
  
      Person *p2 = new Person();
      std::ifstream ifs("Test.txt", std::ifstream::binary);
      //output the right information
      while(ifs.read((char*)p2, sizeof(Person)))
          std::cout &lt;&lt; p2-&gt;getName() &lt;&lt; " " &lt;&lt; p2-&gt;getAge() &lt;&lt; std::endl;
      else
          std::cout &lt;&lt; "Fail" &lt;&lt; std::endl;
      ifs.close();
      return 0;
  }
  </code></pre>
  
  <p>It output the right information.</p>
  
  <p>Why? Thanks.</p>