title: Boost Serialization using polymorphic archives
body: <p>I am working on a client-server application that uses boost::serialization library for it's serialization needs.  </p>
  
  <p>I need to serialize and deserialize polymorphic objects that does not seem to work. The documentation does say that it is supported but none of the related examples demonstrate what I'm trying to do here. So, I am not very sure. My question is can serialize/deserialize polymorphic objects using boost? If yes, what am I doing wrong here?  </p>
  
  <p>Thanks!  </p>
  
  <p>code:  </p>
  
  <pre><code>using namespace std;  
  
  class base {  
    public:
      int data1;  
  
      friend class boost::serialization::access;  
  
      void serialize(boost::archive::polymorphic_iarchive &amp; ar, 
                     const unsigned int file_version) {  
          ar &amp; data1;  
      }  
  
      void serialize(boost::archive::polymorphic_oarchive &amp; ar, 
                     const unsigned int file_version){  
          ar &amp; data1;  
      }  
  
    public:  
      base() {};  
      base(int _d) : data1(_d) {}  
      virtual void foo() const {std::cout &lt;&lt; "base" &lt;&lt; std::endl;}  
  };  
  
  class derived : public base {  
    public:  
      int data2;  
  
      friend class boost::serialization::access;  
  
      void serialize(boost::archive::polymorphic_iarchive &amp; ar, 
                     const unsigned int file_version) {  
          ar &amp; boost::serialization::base_object&lt;base&gt;(*this) &amp; data2;  
      }  
  
      void serialize(boost::archive::polymorphic_oarchive &amp; ar, 
                     const unsigned int file_version){  
          ar &amp; boost::serialization::base_object&lt;base&gt;(*this) &amp; data2;  
      }  
  
    public:  
      derived() {};  
      derived(int _b, int _d) : base(_b), data2(_d) {}  
      virtual void foo() const {std::cout &lt;&lt; "derived" &lt;&lt; std::endl;}  
  };  
  
  int main(int argc, char *argv[]) {  
      // client  
      const base *b1 = new derived(1, 2);  
  
      std::ostringstream oss;  
      boost::archive::polymorphic_text_oarchive oa(oss);  
      oa &lt;&lt; *b1;  
  
      // server  
      base *b2 = new derived(3, 4);  
  
      std::istringstream iss(oss.str());  
      boost::archive::polymorphic_text_iarchive ia(iss);  
      ia &gt;&gt; *b2;  
  
      // prints 1, ok  
      cout &lt;&lt; b2-&gt;data1 &lt;&lt; endl;  
  
      // prints 4, why wasn't the derived class data written?
      cout &lt;&lt; (dynamic_cast&lt;derived*&gt;(b2))-&gt;data2 &lt;&lt; endl;  
  
      return 0;  
  }  
  </code></pre>