title: Reading and writing classes with pointers to binary files in c++
body: <p>I've been trying to write some data to a binary file in c++ using fstream and most examples go like this: </p>
  
  <pre><code>#include &lt;fstream&gt;
  
  class Person{
  public:
      int age;
      char name[50]; 
  }
  
  int main(){
      Person joe;
      joe.age = 50;
      strncpy(joe.name, "Joe Jones");
      fstream file("filename.dat", ios_base::binary);
      file.write((char*)joe, sizeof(joe));
      file.close();
  }
  </code></pre>
  
  <p>This works just as expected but the problem arises when I try to write a more complex structure, mainly one with pointers instead of the actual data.</p>
  
  <pre><code>class Person{
  public:
      int age;
      int *friendsAges;
      Person(int friends){
          friendsAges = new int[friends];
      }
  }
  </code></pre>
  
  <p>When I write the data like before</p>
  
  <pre><code>Person joe(10);
  /* Initialize rest of joe */
  file.write((char*)joe, sizeof(joe));
  </code></pre>
  
  <p>the resulting file has 8 bytes of data, 4 for the <code>age</code> and 4 for the address of the <code>friendsAges</code> array or so it seems.</p>
  
  <p>How could I go about writing the actual data that is stored in the array? I have also had this problem when my classes have other classes as members such as a <code>Person</code> having a <code>Car</code> or something like that.</p>