The problem is that you're saving the derived type and loading the base type. If you want to load through a base class pointer, you have to save through a base class pointer. change DerivedNode* n1 = new DerivedNode(); DerivedNode* n2 = new DerivedNode(); DerivedNode* n3 = new DerivedNode(); to BaseNode* n1 = new DerivedNode(); BaseNode* n2 = new DerivedNode(); BaseNode* n3 = new DerivedNode(); Robert Ramey Jens Weggemann wrote:
Hello,
I've been trying out boost::serialization and ran into a problem trying to serialize objects of derived classes. I set up this simple class hierarchy:
class BaseNode { std::vector
children_; ... friend class boost::serialization::access; template<class Archive> void serialize(Archive &ar, unsigned version) { ar & children_; } }; class DerivedNode : public BaseNode { ... friend class boost::serialization::access; template<class Archive> void serialize(Archive &ar, unsigned version) { ar & boost::serialization::base_object<BaseNode>(*this); } }; All works fine as long as I register the types with the archives:
arch.register_type(static_cast
(NULL)); arch.register_type(static_cast (NULL)); Now the documentation suggests exporting the classes as an alternative to that. But when I instead put
BOOST_CLASS_EXPORT(BaseNode) BOOST_CLASS_EXPORT(DerivedNode)
the polymorphism is not handled correctly and e.g. a tree of 3 DerivedNodes is restored as a single BaseNode object. What am I missing here?
The full code for this test is at http://noonti.de/tree_serialization.cpp.txt
Thanks,
Jens