Object serialization question

Hey all,

I have an ABC Employee class that derives the following classes:
Commission --> Commission + Salary
Hourly
Salary

I am trying to develop methods that will write a single object to a file--which I believe I've been successful in doing--and another method to load (read back in) data. Here's my "Write" method:

void Employee::Write()
{
int size;
WORKER_TYPES type = this->GetType();

char filename[50];
strcpy(filename, m_LastName);
strcat(filename, ".dat");

ofstream outfile(filename, ios::binary);
if (!outfile)
{
cerr << "ERROR:aa This data cannot be saved!" << endl
<< "The file '" << filename << "' cannot be created!" << endl;
return;
}

// first write type to file
outfile.write( reinterpret_cast<const char *>(&type), sizeof(type) );

// now figure out what type of Employee we're saving
if ( typeid(*this) == typeid(Commission) )
size = sizeof(Commission);
else if ( typeid(*this) == typeid(Hourly) )
size = sizeof(Hourly);
else if ( typeid(*this) == typeid(Salary) )
size = sizeof(Salary);
else if ( typeid(*this) == typeid(SalaryPlusCommission) )
size = sizeof(SalaryPlusCommission);
else // error, invalid Employee type
exit(1);

// write object data to file
outfile.write(reinterpret_cast(this), size);

outfile.close();

cout << endl << "Data successfully saved to file '" << filename << "'" << endl;
}

However, every time I try a similar Read method, the program crashes. The I/O methods are NOT virtual, they are declared in the base class. If anyone could show me an appropriate read method I'd be most grateful!

What I'm confused by is, the Write() method seems to be doing everything correctly: I write the object type FIRST, then the object. In my read method (I'd post it, but I currently removed it and am trying out other ideas) first reads in the type, then based on the type creates a new object (Commission, Salary, Hourly, or SalaryPlusCommission), then reads in the data. Help!! :)

Comments

  • : What I'm confused by is, the Write() method seems to be doing everything
    : correctly: I write the object type FIRST, then the object.

    What do these objects look like? Do they have any dynamically allocated members, or member objects that allocate memory dynamically (like std::vector or std::string)? You can't just do a binary dump of such an object -- when you read it back in the pointers will be initialized with bogus values, and your app will crash.

    On a side note, that whole typeid business is very C-like. In C++ you would typically have a virtual member that's overridden in each derived class to do the right thing.

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion