You need to implement a serialization method. Any class that needs to be serialized should know how to selialize and deserialize itself. You can choose one of the common human readable formats available formats, such as JSON, XML etc. You also have the option of using more compact formats such as Google protocol buffers, Apache thrift, or msgpack. If your serilization needs are very simple, then another option is to roll out your own. Here is a full compilable version of the answer given by Neil Krik which should help your understanding . . .
#include <iostream>
#include <vector>
#include <sstream>
#include <assert.h>
#include <fstream>
using namespace std;
class Example
{
vector<int> nums;
public:
explicit Example(vector<int> s = {}) : nums(s)
{
}
vector<int>& getNums()
{
return nums;
}
vector<int> getNums() const
{
return nums;
}
string stringify() const
{
stringstream s;
for (auto x : nums) {
s << x << ", ";
}
return s.str();
}
friend ostream& operator << (ostream& os, const Example& x)
{
os << x.getNums().size() << " ";
for (auto n : x.getNums())
{
os << n << " ";
}
assert(os.good());
return os;
}
friend istream& operator >> (istream& is, Example& x)
{
vector<int>::size_type size;
is >> size;
x.getNums().resize(size);
for (auto& n : x.getNums())
{
is >> n;
}
assert(is.good());
return is;
}
};
int main()
{
// Example 1
string store;
{
ostringstream outfile;
Example x( {1,2,3,4,5,4,3,2,1} );
outfile << x;
store = outfile.str();
}
{
istringstream infile(store);
Example x;
infile >> x;
std::cout << x.stringify() << std::endl;
}
// Example 2
{
ofstream outfile("myfile.txt");
Example x( {1,2,3,4,1,2,3,4} );
outfile << x;
}
{
ifstream infile("myfile.txt");
Example x;
infile >> x;
std::cout << x.stringify() << std::endl;
}
return 0;
}