Boost logo

Boost Users :

Subject: [Boost-users] boost serialization not working unless you have at least one virtual function in base
From: Martin Seiler (seilerm_at_[hidden])
Date: 2009-02-09 05:40:29


Hi all,

Does anybody know why this is the case?

Is there a way to make a class "polymorphic" without adding a dummy virtual
function?
Is this some "silly" optimization done by C++ compilers? Not generating
vtables?

It took me quite some time to figure this one out.
It is mentioned in the documentation (2 lines, easily missed).
http://www.boost.org/doc/libs/1_37_0/libs/serialization/doc/serialization.html#derivedpointers

Maybe add a big huge WARNING? Also please mention this fact in the examples!
(like in demo.cpp?)

regards

M. Seiler

#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/base_object.hpp>
#include <boost/serialization/type_info_implementation.hpp>
#include <boost/serialization/export.hpp>
#include <boost/archive/archive_exception.hpp>
#include <boost/archive/basic_xml_archive.hpp>

class A
{
public:
    A() : test(33)
    {
    }
    int test;
    virtual void dummy(){} // if you comment this line it won't work
};

class B : public A
{
public:
    B() : test_b(52)
    {
    }
    int test_b;
    virtual void foo(){};
};
namespace boost {
    namespace serialization {
        template<class Archive>
        void serialize(Archive & ar, A & o, const unsigned int version)
        {
            ar & make_nvp("test", o.test);
        }
        template<class Archive>
        void serialize(Archive & ar, B & o, const unsigned int version)
        {
            ar & boost::serialization::make_nvp("A",
boost::serialization::base_object<A>(o));
            ar & make_nvp("test_b", o.test_b);
        }
    }
}

BOOST_CLASS_EXPORT(B); // Should register B for all archives such that it
can be serialized of the basepointers

void main()
{
    A* a = new B();

    boost::archive::xml_oarchive archive(std::cout);

    archive.template register_type<B>(); // Should register B for this
archive

    archive & boost::serialization::make_nvp ("a", a);

    // If you check the output, you see that `{B}.test_b' was not serialized

    int i;
    std::cin >> i;

}



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