Boost logo

Boost Users :

From: Jason Gorski (gorski_at_[hidden])
Date: 2007-08-16 09:54:54


Hello,

I have been using the Boost Serialization libraries on a project of mine
and so far they have worked very well. However, I have been unable to
properly load derived objects using a base class pointer. The following
code generates an unregistered class exception:

#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
#include <sstream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/export.hpp>

class Base_Class
{
 public:
  
  friend class boost::serialization::access;

  template<class Archive>
  void serialize(Archive & ar, const unsigned int version)
  {
    // empty
  }

  virtual void print()=0;
};

class Derived_Class: public Base_Class
{
 public:
 
  int i1;
  int i2;
  int i3;
 
  friend class boost::serialization::access;

  template<class Archive>
  void serialize(Archive & ar, const unsigned int version)
  {
    ar & boost::serialization::base_object<Base_Class>(*this);
    ar & i1;
    ar & i2;
    ar & i3;
  }
 
  void print(){
    std::cout << "i am a derived class object" << std::endl;
  }

};

BOOST_CLASS_EXPORT(Derived_Class)

/*****************************************
 Main
 *****************************************/
int main()
{

  Derived_Class derived_send;
  derived_send.i1=12;
  derived_send.i2=13;
  derived_send.i3=14;
 
 
  Base_Class * base_ptr;
  Derived_Class * derived_recv;

  // save derived class
  std::ostringstream output_stream;
  boost::archive::text_oarchive output_archive( output_stream );
  output_archive & derived_send;
 
 
  // load using base class ptr
  std::istringstream input_stream( output_stream.str() );
  boost::archive::text_iarchive input_archive( input_stream );
  input_archive & base_ptr;

  derived_recv = (Derived_Class*) base_ptr;
  derived_recv->print();

}

 From reading the documentation, it seems as if this should work fine.
Am I missing something?

Thanks in advance,
Jason

-- 
Jason Gorski
Research Engineer
Oasis Advanced Engineering, Inc.
(248)373-9800 x 269
gorski_at_[hidden] 

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