problem about boost::serialization library
Jun 10, 2011 at 6:50am UTC
i am using boost serialization library. I have a child class deriving from parent class. Both classes have their serialization function. When I want to hold a child class object through a parent class ptr and want to write it to a file, the parent serialization function is called instead of child class's serialization function. how to solve the problem?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
#include <iostream>
#include <fstream>
#include <boost/shared_ptr.hpp>
#include <boost/filesystem.hpp>
#include <boost/serialization/version.hpp>
#include <boost/serialization/split_member.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
using namespace std;
using boost::shared_ptr;
using namespace boost::filesystem;
using namespace boost::archive;
class Parent {
friend class boost::serialization::access;
template <class Archive> void save(Archive & ar,const unsigned int version) const ;
template <class Archive> void load(Archive & ar,const unsigned int version);
BOOST_SERIALIZATION_SPLIT_MEMBER()
public :
Parent();
virtual ~Parent() = 0;
};
Parent::Parent() {cout<<"Parent()" <<endl;}
Parent::~Parent() {cout<<"~Parent()" <<endl;}
template <class Archive>
void Parent::save(Archive & ar,const unsigned int version) const {cout<<"Parent::save" <<endl;}
template <class Archive>
void Parent::load(Archive & ar,const unsigned int version) {cout<<"Parent::load" <<endl;}
class Child : public Parent {
friend class boost::serialization::access;
template <class Archive> void save(Archive & ar,const unsigned int version) const ;
template <class Archive> void load(Archive & ar,const unsigned int version);
BOOST_SERIALIZATION_SPLIT_MEMBER()
public :
Child() {cout<<"Child()" <<endl;}
~Child() {cout<<"~Child()" <<endl;}
};
template <class Archive>
void Child::save(Archive & ar,const unsigned int version) const {cout<<"Child::save" <<endl;}
template <class Archive>
void Child::load(Archive & ar,const unsigned int version) {cout<<"Child::load" <<endl;}
int main()
{
shared_ptr<Parent> p(new Child());
ofstream out("test.txt" );
text_oarchive ofs(out);
ofs << *p;
}
you can compile the program through
g++ test.cpp -lboost_filesystem -lboost_serialization
the output of the program is
Parent()
Child()
Parent::save
~Child()
~Parent()
Last edited on Jun 10, 2011 at 6:52am UTC
Jun 10, 2011 at 7:52am UTC
Your save() and load() functions must be virtual (at least in your class Parent).
Topic archived. No new replies allowed.