I've read through loads of similar questions but haven't found the answer. I'm using Visual Studio 2010 and boost 1.47.
Here's the code, it's complete and compilable:
#include "stdafx.h"
#include <string>
#include <sstream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/export.hpp>
using namespace std;
class BaseObject
{
public:
BaseObject(void) { };
virtual ~BaseObject(void) { };
template<class Archive>
void serialize(Archive &ar, const unsigned int version)
{ /* nothing happens here */ };
};
class DerivedObject : public BaseObject
{
public:
string text;
public:
DerivedObject(void) { };
~DerivedObject(void) { };
template<class Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & text;
};
};
BOOST_CLASS_EXPORT(DerivedObject)
int _tmain(int argc, _TCHAR* argv[])
{
DerivedObject der;
der.text = "Testing!";
std::ostringstream os;
boost::archive::text_oarchive oa(os);
oa.register_type<DerivedObject>();
// I made a DerivedObject, but I'm casting it to a BaseObject
// as the serialization code should not have to know what type it is
BaseObject *base = &der;
// now serialize it
oa << *base;
printf("serialized: %s\r\n",os.str().c_str());
return (0);
}
You can see it's real simple, and I've added the BOOST_CLASS_EXPORT and oa.register_type magic that's supposed to make sure DerivdObject::serialize() is called even though it isn't a virtual method.. but still only serialize() in BaseObject is called. A problem specific to Visual C++ perhaps? Please advice?
As described in the boost serialization documentation you need to tell your derived class to call the base class serialization code. Just write your derived class serialize method like this :
template<class Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & boost::serialization::base_object<BaseObject>(*this);
ar & text;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With