serialize derived class object through boost::serialization

I want to serialize a derived class object through boost::serialization library. To test whether both the base and the derived class object have been serialized properly, I print message to the console when the serialize function is called. When the following code is compiled and runned, the message of serialize function for the base class object is not shown. Thus, the base class object is not serialized properly. Why the serialization is not done on the base class object? #include <cstdlib> #include <iostream> #include <fstream> #include <boost/serialization/version.hpp> #include <boost/serialization/export.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/shared_ptr.hpp> using namespace std; using namespace boost::archive; using boost::shared_ptr; class Base { friend class boost::serialization::access; template<class Archive> void serialize(Archive & ar, const unsigned int version); protected: int a; public: Base():a(0){} virtual ~Base(){} int geta() const {return a;} void seta(int aa) {a = aa;} }; template<class Archive> void Base::serialize(Archive & ar,const unsigned int version) { cout<<"serializing base class object"<<endl; ar & a; } class Derived : public Base { friend class boost::serialization::access; template<class Archive> void serialize(Archive & ar, const unsigned int version); protected: int b; public: Derived():Base(),b(0){} virtual ~Derived(){} int getb() const {return b;} void setb(int bb) {b = bb;} }; template<class Archive> void Derived::serialize(Archive & ar,const unsigned int version) { boost::serialization::base_object<Base>(*this); boost::serialization::void_cast_register<Derived,Base> ( static_cast<Derived*>(NULL), static_cast<Base*>(NULL) ); cout<<"serializing derived class object"<<endl; ar & b; } BOOST_CLASS_EXPORT_GUID(Derived,"Derived"); int main(int argc,char ** argv) { shared_ptr<Base> ptr(new Derived()); ptr->seta(4); Base * p = ptr.get(); Derived * pp = dynamic_cast<Derived*>(p); assert(pp); pp->setb(4); ofstream out("test.dat"); text_oarchive oa(out); oa << p; return EXIT_SUCCESS; }

template<class Archive>void Derived::serialize(Archive & ar,const unsigned int version){ ar & boost::serialization::base_object<Base>(*this); // add ar & boost::serialization::void_cast_register<Derived,Base> (static_cast<Derived*>(NULL), static_cast<Base*>(NULL) ); cout<<"serializingderived class object"<<endl; ar & b;}BOOST_CLASS_EXPORT_GUID(Derived,"Derived"); I just checked the documenation and see that there is a mistake in the example. I'll fix this. Robert Ramey
_______________________________________________ Boost-users mailing list Boost-users@lists.boost.org http://lists.boost.org/mailman/listinfo.cgi/boost-users
participants (2)
-
breadbread1984
-
Robert Ramey