Boost logo

Boost Users :

Subject: [Boost-users] Serialize abstract base class
From: Fabian Weiss (fabian.weiss_at_[hidden])
Date: 2011-11-02 18:45:30


I try to serialize objects wich are derived of an abstract base class.

class Modul()
{
    Modul();
    int a;

    virtual void function() = 0;

  private:
    friend class boost::serialization::access;

    template <typename Archive>
    void serialize(Archive &ar, const unsigned int version)
    {
      ar & boost::serialization::make_nvp("a", a);
    };
};

BOOST_SERIALIZATION_ASSUME_ABSTRACT(Modul)
BOOST_CLASS_TRACKING(Modul, track_never)

class ExampleModul : public Modul
{
    ExampleModul(){};

    int b;

    void function();

  private:
    friend class boost::serialization::access;

    template <typename Archive>
    void serialize(Archive &ar, const unsigned int version)
    {
      ar & boost::serialization::make_nvp("Modul",
boost::serialization::base_object<Modul>(*this));
      ar & boost::serialization::make_nvp("b", b);
    }

};

For serializing the classes I use a boost::archive::xml_oarchive and
register the classes:

  boost::archive::xml_oarchive archfile;
  archfile.register_type<Modul>();
  archfile.register_type<ExampleModul>();

I can compile serializing and run the code - works. But when it comes to
deserializing I get a compile error:

..instantiated from here
/usr/include/boost/serialization/access.hpp:132:9: error: cannot
allocate an object of abstract type 'Modul'
note: because the following virtual functions are pure within 'Modul':
virtual void Modul::function()

If I do not register <Modul> in the deserializing code, then it compiles
but I get runtime error of course: terminate called after throwing an
instance of 'boost::archive::archive_exception'

I found this example but I dont understand what they are doing and where
the classes are registered:
http://www.boost.org/doc/libs/1_47_0/libs/serialization/example/demo.cpp

How can I serialize my abstract base class?


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