Boost logo

Boost Users :

Subject: [Boost-users] serialize derived class object through boost::serialization
From: breadbread1984 (breadbread1984_at_[hidden])
Date: 2012-04-28 05:56:04


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;
}



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