Three show stopping problems in this code: a) A doesn't have serialize method even though such a method is invoked by base object. see: http://www.boost.org/libs/serialization/doc/serialization.html b) saving a non-const object - see rationale section c) Main show stopper:
int main() { // Create a B object B* Child = new B;
// Set some data std::string Data = "test"; Child->SetValue( Data );
// Assign it to a A ptr // const A* Parent = Child; // ****** note new const - see rationale
// create and open a character archive for output std::ofstream ofs( "filename" );
// save data to archive { try { boost::archive::text_oarchive oa( ofs ); // write class instance to archive // *** big problem here. Dereferecing pointer to A yields a ref // *** to an A - regardless that ptr was a B. What you really want is: oa << Parent; // *** let serialization handle dererencing // *** instead of: //oa << *Parent; } catch( boost::archive::archive_exception& e ) { std::cout << "Save failed! : " << e.what(); std::cout.flush();
return false; } catch( ... ) { std::cerr << "Unknown Exception " << std::endl;
return false; }
// archive and stream closed when destructors are called }
delete Child; }