Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost serialization of derived object doesn't call derived's serialize()

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?

like image 666
CodeOrElse Avatar asked Mar 15 '12 10:03

CodeOrElse


1 Answers

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;
  };
like image 116
Julien Hirel Avatar answered Oct 15 '22 04:10

Julien Hirel