title: Class Serialization methods
body: <p>I want to serialize objects in c++. At first I tried a simple solution, I overloaded the <code>&lt;&lt;</code> and <code>&gt;&gt;</code> operators of the class to serialize; This way I can select witch attribute to serialize into a strinstream and I can then deserialize the same stringstream into the attribute of another object of the same type later on.
  That worked until I realized that if the class to serialize contains pointers to other classes then I would need to overload their <code>&gt;&gt;</code> and <code>&lt;&lt;</code> operators as well.</p>
  
  <p>So I started thinking that what if I get the object to serialize and traverse it char (1 byte) by char and then save the result into a string. Then later on take that string and reinterpret_cast it into the original class. This way I would be able to serialize any class containing any type of information without caring about what it contains and without overloading any operator.</p>
  
  <p>I implemented this second method and it seams to be Ok but is it?</p>
  
  <pre><code>#include &lt;cstdlib&gt;
  #include &lt;iostream&gt;
  #include &lt;vector&gt;
  #include &lt;stdlib.h&gt;
  using namespace std;
  
  class B
  {
  public:
        B(int one , int two)
        { 
              this-&gt;one = one; 
              this-&gt;two = two;
        }
        int one;
        int two;      
  };
  
  class A
  {
  public:
        A(int one , int two, B b)
        {
              this-&gt;one = one; 
              this-&gt;two = two;
              classB= new B(b);
        }
        int one;
        int two;   
        B* classB;   
  };
  
  int main(int argc, char *argv[])
  {
      B b(3,4);
      A* a = new A(1,2, b);
  
  
      //Serializing 'a'
      char v[sizeof(A)];
      for (int i =0 ;i&lt;sizeof(A);i++)
      {
          v[i] = (reinterpret_cast&lt;char*&gt;(a)[i]);
      }
  
      char* cp = (char*)malloc(sizeof(char) * sizeof(A));
      for (int i =0 ;i&lt;sizeof(A);i++)
      { 
          cp[i] = v[i];                          
      }
  
      A* aa = reinterpret_cast&lt;A*&gt;(cp);
  
      cout &lt;&lt; aa-&gt;one &lt;&lt; endl;
      cout &lt;&lt; aa-&gt;two&lt;&lt; endl;
      cout &lt;&lt; aa-&gt;classB-&gt;one&lt;&lt; endl;
  
      free(cp);
      system("PAUSE");
      return EXIT_SUCCESS;
  
  // OUTPUT is as expect:
     1 
     2 
     3
  }
  </code></pre>
  
  <p>So what do you think? do you foresee any complications regarding the second method? Please bare in mind that I am very new to C++ and I am trying to develop working theories.</p>