Boost logo

Boost Users :

From: Robert Ramey (ramey_at_[hidden])
Date: 2008-07-14 17:54:20


The base class MUST be polymorphic - that is have at least one virtual function.

AND the the pointer to the base class - not the derived class should be serialized.

Robert Ramey

  #include "stdafx.h"
  #include "stdafx.h"

   

  #include <sstream>

   

  // include headers that implement a archive in simple text format

  #include <boost/archive/text_oarchive.hpp>

  #include <boost/archive/text_iarchive.hpp>

  #include <boost/serialization/export.hpp>

   

   

  class base {

  public:

      base(){ m_val = 1; }

      void PrintVal( void )

      {

          printf(" Value: %d\n", m_val );

      }

  protected:

  // note:make polymporphic

      virtual void foo(void) = 0;

      friend class boost::serialization::access;

      template<class Archive>

      void serialize(Archive & ar, const unsigned int file_version){

          ar & m_val;

      }

      int m_val;

  };

   

   

  class derived : public base {

  public:

      derived(){ m_val = 2; }

  private:

      void foo(void){}

      friend class boost::serialization::access;

      template<class Archive>

      void serialize(Archive & ar, const unsigned int file_version){

          boost::serialization::base_object<base>(*this);

      }

  };

   

  BOOST_CLASS_EXPORT_GUID(derived, "derived")

   

  void test4(){

      std::stringstream ss;

      boost::archive::text_oarchive oa(ss);

      const base *b = new derived();

      b->PrintVal();

      oa & b;

   

      boost::archive::text_iarchive ar(ss);

      b = NULL;

      ar & b;

      b->PrintVal();

  }

   

  int main() {

      test4();

      return 0;

  }

   

   

------------------------------------------------------------------------------

  _______________________________________________
  Boost-users mailing list
  Boost-users_at_[hidden]
  http://lists.boost.org/mailman/listinfo.cgi/boost-users



Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net