Serializing problem in boost
Hi, I've created little example to train serialize in boost:
Code:
//test.h
#ifndef TEST_H
#define TEST_H
#include <iostream>
#include <fstream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/base_object.hpp>
#include <boost/serialization/export.hpp>
using namespace std;
class test
{
private:
int number1;
int number2;
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & Ar, const int version){
Ar & number1;
Ar & number2;
}
public:
test() { number1=100; number2=20;}
virtual void power() {cout << "test power\n";}
void save();
void load();
};
class subtest : public test
{
private:
int number3;
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar,const unsigned int version)
{
ar & boost::serialization::base_object<test>(*this);
ar & number3;
}
public:
subtest() : test() {number3=5;}
virtual void power() {cout << "subtest power\n" << number3;}
};
#endif // TEST_H
//test.cpp
#include "test.h"
void test::save(){
ofstream ofs("uno");
boost::archive::text_oarchive oa(ofs);
oa << *this;
}
void test::load(){
ifstream ifs("uno");
boost::archive::text_iarchive ia(ifs);
ia >> *this;
}
//main.cpp
#include <iostream>
#include <fstream>
#include "test.h"
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/base_object.hpp>
#include <boost/serialization/export.hpp>
BOOST_CLASS_EXPORT_GUID(test, "test")
BOOST_CLASS_EXPORT_GUID(subtest, "subtest")
using namespace std;
int main()
{
int num;
cin >> num;
if(num==1){
ofstream ofs("uno");
boost::archive::text_oarchive oa(ofs);
test * one = new subtest();
oa << one;
one->power();
}
else{
test *two = new test();
ifstream ifs("uno");
boost::archive::text_iarchive ia(ifs);
ia >> two;
two->power();
}
return 0;
}
This way it works. It is saving and loading without a problems. When loading I get wanted results “subtest power and number3”. But when I change code to to use save and load functions from clases it dosen't identyfy derived class and in loading i get “test power”:
Code:
//main changed
int main()
{
int num;
cin >> num;
if(num==1){
test * one = new subtest();
one->save();
one->power();
}
else{
test *two = new test();
two->load();
two->power();
}
return 0;
}
Save and load functions in main and in class are almost identycal. I think I don't know somethink how can I create good save, load functions?